1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>模拟Java中的Map</title> 6 7 <script> 8 9 function Map(){ 10 11 var obj = {}; 12 //put 方法 13 14 this.put = function(key , value){ 15 obj[key] = value; 16 } 17 18 //size 方法 19 20 this.size = function(){ 21 var count = 0; 22 for(var attr in obj){ 23 count++; 24 } 25 return count; 26 } 27 28 //get方法 29 30 this.get = function(key){ 31 //判断key是否存在 32 if(key || obj[key] === 0 || obj[key] === false){ 33 return obj[key]; 34 }else{ 35 return null; 36 } 37 } 38 39 //remove 方法 40 41 this.remove = function(key){ 42 if(key || obj[key] || obj[key] === false){ 43 delete obj[key]; 44 } 45 } 46 47 //eachMap 方法 48 49 this.eachMap = function(fn){ 50 for(var attr in obj){ 51 fn(attr ,obj[attr]); 52 } 53 } 54 55 56 57 } 58 59 60 61 var m = new Map(); 62 m.put(‘1‘,‘123‘); 63 m.put(‘2‘,true); 64 m.put(‘3‘,false); 65 m.put(‘4‘,new Date()); 66 67 alert(m.size()); 68 alert(m.get(‘2‘)); 69 m.remove(‘4‘); 70 m.eachMap(function(key,value){ 71 alert(key + ":" + value); 72 }); 73 74 75 </script> 76 77 78 79 </head> 80 <body> 81 82 </body> 83 </html>
时间: 2024-11-02 01:32:57