JS自定義 Map 鍵值對對象

<script>  
function Map() {
this.keys = new Array();
this.data = new Array();
//添加鍵值對
this.set = function (key, value) {
if (this.data[key] == null) {//如鍵不存在則身【鍵】數組添加鍵名
this.keys.push(value);
}
this.data[key] = value;//給鍵賦值
};
//獲取鍵對應的值
this.get = function (key) {
return this.data[key];
};
//去除鍵值,(去除鍵數據中的鍵名及對應的值)
this.remove = function (key) {
this.keys.remove(key);
this.data[key] = null;
};
//判斷鍵值元素是否爲空
this.isEmpty = function () {
return this.keys.length == 0;
};
//獲取鍵值元素大小
this.size = function () {
return this.keys.length;
};
}

//test
var newMap=new Map();
newMap.set("1","Hello JS");
alert(
newMap.get("1")); 
</script> 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章