Javascript实现的Map集合工具类完整实例

var Map = function(){ // 构造entry实体 var Entry = function(key, value){ this.key = key; this.value = value; } this.entries = new Array(); // 构造put方法在数组中放入一个Entry this.put = function(key, value){ // 数组中已存在就不放入 for (var i = 0; i < this.size(); i++) { if (this.entries[i].key === key) { return false; } } this.entries.push(new Entry(key, value)); }; // 模拟get方法 this.get = function(key){ for (var i = 0; i < this.size(); i++) { if (this.entries[i].key === key) { return this.entries[i].value; } } return null; }; // 查找下标值 this.indexOf = function(key){ var index = -1; for (var i = 0; i < this.size(); i++) { if (this.entries[i].key === key) { index = i; break; } } return index; } // 删除一个元素 this.remove = function(key){ var index = this.indexOf(key); if (index != -1) { this.entries.splice(index, 1); } } // 取得map长度 this.size = function(){ return this.entries.length; }; // 重新设置键值对 this.setValue = function(key, value){ var index = this.indexOf(key); if (index != -1) { this.entries[i].value = value; }; }; // 是否为空map this.isEmpty = function(){ return this.size() <= 0; }; //清空map ; this.clear = function(){ this.entries = []; }; // 得到entry实体 this.getEntry = function(index){ if (index >= 0 && index < this.size()) { return this.entries[index]; } return null; } this.toString = function(){ var str = "["; for (var i = 0; i < this.size(); i++) { str += this.getEntry(i).key + "=" + this.getEntry(i).value + ","; } // 去除最后一个"," str = str.substring(0, str.length - 1); str += "]"; return str; }; }

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wgdwdj.html