首先實現Array的remove方法:
Map的實現基於array , 此代碼是借一達人寫的,我測試的時候,map 的remove 方法不能使用,所以就寫瞭上面array.remove方法
view plaincopy to clipboardprint?function Map() {
/** 存放鍵的數組(遍歷用到) */
this.keys = new Array();
/** 存放數據 */
this.data = new Object();
/**
* 放入一個鍵值對
* @param {String} key
* @param {Object} value
*/
this.put = function(key, value) {
if(this.data[key] == null){
this.keys.push(key);
}
this.data[key] = value;
};
/**
* 獲取某鍵對應的值
* @param {String} key
* @return {Object} value
*/
this.get = function(key) {
return this.data[key];
};
/**
* 刪除一個鍵值對
* @param {String} key
*/
this.remove = function(key) {
this.keys.remove(key);
this.data[key] = null;
};
/**
* 遍歷Map,執行處理函數
*
* @param {Function} 回調函數 function(key,value,index){..}
*/
this.each = function(fn){
if(typeof fn != 'function'){
return;
}
var len = this.keys.length;
for(var i=0;i<len;i++){
var k = this.keys[i];
fn(k,this.data[k],i);
}
};
/**
* 獲取鍵值數組(類似Java的entrySet())
* @return 鍵值對象{key,value}的數組
*/
this.entrys = function() {
var len = this.keys.length;
var entrys = new Array(len);
for (var i = 0; i < len; i++) {
entrys[i] = {
key : this.keys[i],
value : this.data[i]
};
}
return entrys;
};
/**
* 判斷Map是否為空
*/
this.isEmpty = function() {
return this.keys.length == 0;
};
/**
* 獲取鍵值對數量
*/
this.size = function(){
return this.keys.length;
};
}
function Map() {
/** 存放鍵的數組(遍歷用到) */
this.keys = new Array();
/** 存放數據 */
this.data = new Object();
/**
* 放入一個鍵值對
* @param {String} key
* @param {Object} value
*/
this.put = function(key, value) {
if(this.data[key] == null){
this.keys.push(key);
}
this.data[key] = value;
};
/**
* 獲取某鍵對應的值
* @param {String} key
* @return {Object} value
*/
this.get = function(key) {
return this.data[key];
};
/**
* 刪除一個鍵值對
* @param {String} key
*/
this.remove = function(key) {
this.keys.remove(key);
this.data[key] = null;
};
/**
* 遍歷Map,執行處理函數
*
* @param {Function} 回調函數 function(key,value,index){..}
*/
this.each = function(fn){
if(typeof fn != 'function'){
return;
}
var len = this.keys.length;
for(var i=0;i<len;i++){
var k = this.keys[i];
fn(k,this.data[k],i);
}
};
/**
* 獲取鍵值數組(類似Java的entrySet())
* @return 鍵值對象{key,value}的數組
*/
this.entrys = function() {
var len = this.keys.length;
var entrys = new Array(len);
for (var i = 0; i < len; i++) {
entrys[i] = {
key : this.keys[i],
value : this.data[i]
};
}
return entrys;
};
/**
* 判斷Map是否為空
*/
this.isEmpty = function() {
return this.keys.length == 0;
};
/**
* 獲取鍵值對數量
*/
this.size = function(){
return this.keys.length;
};
}
作者“huilixiang的專欄”