javascript 自定義對(duì)象實(shí)現(xiàn)Java中的Map對(duì)象功能
Java中有集合,Map等對(duì)象存儲(chǔ)工具類,這些對(duì)象使用簡易,但是在JavaScript中,你只能使用Array對(duì)象。
這里我創(chuàng)建一個(gè)自定義對(duì)象,這個(gè)對(duì)象內(nèi)包含一個(gè)數(shù)組來存儲(chǔ)數(shù)據(jù),數(shù)據(jù)對(duì)象是一個(gè)Key,可以實(shí)際存儲(chǔ)的內(nèi)容!
這里Key,你要使用String類型,和Java一樣,你可以進(jìn)行一些增加,刪除,修改,獲得的操作。
使用很簡單,我先把工具類給大家看下:
/** * @version 1.0 * @author cuisuqiang@163.com * 用于實(shí)現(xiàn)頁面 Map 對(duì)象,Key只能是String,對(duì)象隨意 */ var Map = function(){ this._entrys = new Array(); this.put = function(key, value){ if (key == null || key == undefined) { return; } var index = this._getIndex(key); if (index == -1) { var entry = new Object(); entry.key = key; entry.value = value; this._entrys[this._entrys.length] = entry; }else{ this._entrys[index].value = value; } }; this.get = function(key){ var index = this._getIndex(key); return (index != -1) ? this._entrys[index].value : null; }; this.remove = function(key){ var index = this._getIndex(key); if (index != -1) { this._entrys.splice(index, 1); } }; this.clear = function(){ this._entrys.length = 0;; }; this.contains = function(key){ var index = this._getIndex(key); return (index != -1) ? true : false; }; this.getCount = function(){ return this._entrys.length; }; this.getEntrys = function(){ return this._entrys; }; this._getIndex = function(key){ if (key == null || key == undefined) { return -1; } var _length = this._entrys.length; for (var i = 0; i < _length; i++) { var entry = this._entrys[i]; if (entry == null || entry == undefined) { continue; } if (entry.key === key) {//equal return i; } } return -1; }; } 如果你不懂Js中對(duì)象的創(chuàng)建等一些基礎(chǔ)知識(shí),自己可以網(wǎng)上查一下。
// 自定義Map對(duì)象 var map = new Map(); map.put("a","a"); alert(map.get("a")); map.put("a","b"); alert(map.get("a")); 先彈出 a 后面彈出 b ,因?yàn)楹竺娴臅?huì)覆蓋前面的!
如有疑問請(qǐng)留言或者到本站社區(qū)交流討論,感謝閱讀,希望能幫助到大家,謝謝大家對(duì)本站的支持!
新聞熱點(diǎn)
疑難解答
圖片精選