[JS] 簡單map實現 (普通和 jquery 版本)

來源:互聯網
上載者:User

閑來無事寫了個javascript 版本的map,希望能用最少的代碼實現以下功能: 儲存key-value對 取key-value對 用數組的方法遍曆map

首先我們來看下普通的版本:

(function($){ $.imap = function(){ var imap = this.map = {}; this.get = function(key){ var val = eval("imap."+key); return (typeof val === undefined) ? null : val; }; this.set = function(key,value){ eval("imap."+key+"=value"); }; }; })(window);

 

接下來是測試案例呵呵。。

var map = new window.imap(); 19 map.set('strKey','hello world'); 20 document.write("the value of key 'strKey' in map is " + map.get('strKey')+"<br/ >"); 21 22 var obj = { a : 'z'}; 23 map.set('objKey' , obj); 24 document.write("the value of key 'objKey' in map is " + map.get('objKey')+"<br/ >");

 

 

遍曆map的所有元素:

for(var ele in map.map){ document.write("key:"+ele +"//value:"+ map.get(ele)+"<br/>"); }

 

只要將上面的window 換成 “$”就是juqery的版本了,很方便吧。

 

上述版本是基於對象實現的map,所以這裡有個限制 :map的key值不能為數字開頭的key

 

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.