javascript實(shí)現(xiàn)Java中的Map對(duì)象功能的實(shí)例詳解
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ì)本站的支持!
相關(guān)文章
深入理解JavaScript系列(47):對(duì)象創(chuàng)建模式(上篇)
這篇文章主要介紹了深入理解JavaScript系列(47):對(duì)象創(chuàng)建模式(上篇),本文講解了命名空間、定義依賴、私有屬性和私有方法 、Revelation模式、鏈模式等內(nèi)容,需要的朋友可以參考下2015-03-03
javascript?DOM?querySelectorAll()?使用方法
querySelectorAll()?方法返回文檔中匹配指定?CSS?選擇器的所有元素,返回?NodeList?對(duì)象,一般用來獲取指定id火class下的所有節(jié)點(diǎn)2023-06-06
Javascript基礎(chǔ)教程之?dāng)?shù)據(jù)類型 (數(shù)值 Number)
本文講述的是javascript中九種數(shù)據(jù)類型的第二種--數(shù)值(Number),使用非常簡單,這里推薦給小伙伴們。2015-01-01
Javascript Object 對(duì)象學(xué)習(xí)筆記
這篇文章主要介紹了Javascript Object 對(duì)象學(xué)習(xí)筆記,需要的朋友可以參考下2014-12-12
詳解JavaScript中的數(shù)據(jù)類型,以及檢測(cè)數(shù)據(jù)類型的方法
這篇文章主要介紹了JavaScript中的數(shù)據(jù)類型,以及檢測(cè)數(shù)據(jù)類型的方法,幫助大家鞏固基礎(chǔ)知識(shí),感興趣的朋友可以了解下2020-09-09
JS中構(gòu)造函數(shù)的基本特性與優(yōu)缺點(diǎn)
這篇文章介紹了JS中構(gòu)造函數(shù)的基本特性與優(yōu)缺點(diǎn),文中通過示例代碼介紹的非常詳細(xì)。對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-06-06

