JavaScript 自定義map

第一種方法使用Object實現:

<script type="text/javascript">

Map = function(){

this.obj = new Object();

this.put = function(key ,value)

{

this.obj[key] = value ; 

}

this.size = function(){

var count = 0 ;

for( var  attr in this.obj){

count++;

}

return count;

}

this.get = function(key)

{

if(this.obj[key] || this.obj[key] === 0 || this.obj[key] === null )

{

return this.obj[key];

//return this.obj.key;

}else{

return null;

}


}

this.remove = function(key){

if(this.obj[key] || this.obj[key] === 0 || this.obj[key] === null )

{

//delete this.obj[key];

}else{

return null;

}

}

this.eachMap = function(fn){

for(var attr in this.obj){

fn(attr,this.obj[attr]);

}

}

}

var map =new Map();

map.put('01', 'a');

map.put('02', 'b');

map.put('C', 'c');

map.put('D', 'd');

//alert(map.size());

//alert(map.get('C'));

//alert(map.get('C'));

//map.remove('01');

//alert(map.get('01'));


map.eachMap(function(key , value){

alert(key+" "+value);

});

</script>


第二種方法使用Array數組實現

  <script type="text/javascript">

Map = function()

{

this.elements = new Array();

this.size = function()

{

return this.elements.length;

}

this.put = function(_key,_value)

{

this.elements.push({

key:_key,

value:_value

});

}

this.isEmpty = function()

{

var flag = true;

if(0==this.size())

{

flag = true;

}else

{

flag = false;

}

return flag;

}

this.clear = function()

{

this.elements = new Array();

}

this.remove = function(_key)

{

flag =false

try

{

for(var i=0;i<this.elements.length;i++)

{

if(this.elements[i].key == _key)

{

this.elements.splice(i,1);

}

}

flag = true;

}

catch (e)

{

flag = false;

}

return this.flag;

}

}


var map = new Map();

console.info(map);

alert(map.size());

map.put("hello","world");

map.put('world','welcome');

alert(map.size());

console.info(map);

alert(map.isEmpty());

console.info(document);

console.info(document.getElementById("myform"));


  </script>

發佈了26 篇原創文章 · 獲贊 1 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章