javascript map的实现 发表于 2015-10-03 | 分类于 Web | 引言 在java语言中,map是一种重要的数据结构; 在js中,没有现成的map实现; 本文就带您来实现js中的map; map的具体实现12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849function Map(){ this.keys = new Array(); this.data = new Object(); this.put = function(key,value){ if(this.data[key]==null){ this.keys.push(key); } this.data[key] = value; } this.get = function(key){ return this.data[key]; } this.remove = function(key){ var index = this.keys.indexOf(key); this.keys.splice(index,1); this.data[key] = null; } this.containsKey = function(key){ if(this.keys.indexOf(key)!= -1){ return true; }else{ return false; } } this.size = function(){ return this.keys.length; } this.entrySet = 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[this.keys[i]] }; } return entrys; } this.isEmpty = function(){ return this.keys.length == 0; }} 自定义map的使用1234567891011121314151617181920//定义mapvar map = new Map();map.put("name","xiaozhang");map.put("age",20);map.put("home","beijing");//遍历mapvar arr = map.entrySet();for(var i =0; i<arr.length; i++){ document.write(arr[i].key+":"+arr[i].value+"<br>");}//获取 移除元素map.get("name"); // xiaozhangmap.remove("home");//其他方法map.containsKey("name"); // truemap.size(); // 2map.isEmpty(); // false 您的支持是对我最大的鼓励! 赏 微信打赏 支付宝打赏