javascript實現Map結構

來源:互聯網
上載者:User

標籤:try   清空   nta   根據   var   empty   this   sem   def   

//定義map function Map() { this.container = {};}//將key-value放入map中 Map.prototype.put = function(key, value) { try { if (key != null){ this.container[key] = value; } } catch (e) { return e; }};//根據key從map中取出對應的value Map.prototype.get = function(key,deft) { if(!this.containsKey(key)){ return deft; } try { return this.container[key]; } catch (e) { return e; }};//判斷map中是否包含指定的key Map.prototype.containsKey = function(key) { try { for ( var p in this.container) { if (p == key) return true; } return false; } catch (e) { return e; }}//判斷map中是否包含指定的value Map.prototype.containsValue = function(value) { try { for ( var p in this.container) { if (this.container[p] === value) return true; } return false; } catch (e) { return e; }};//刪除map中指定的key Map.prototype.remove = function(key) { try { delete this.container[key]; } catch (e) { return e; }};//清空map Map.prototype.clear = function() { try { delete this.container; this.container = {}; } catch (e) { return e; }};//判斷map是否為空白 Map.prototype.isEmpty = function() { if (this.keySet().length == 0) return true; else return false;};//擷取map的大小 Map.prototype.size = function() { return this.keySet().length;}//返回map中的key值數組 Map.prototype.keySet = function() { var keys = new Array(); for ( var p in this.container) { keys.push(p); } return keys;}//遍曆MapMap.prototype.each = function(fun){ var keys = this.keySet(); for(var i = 0;i < keys.length;i++){ fun(keys[i],this.get(keys[i])); }}//返回map中的values值數組 Map.prototype.values = function() { var valuesArray = new Array(); var keys = this.keySet(); for (var i = 0; i < keys.length; i++) { valuesArray.push(this.container[keys[i]]); } return valuesArray;}//擷取Map的最大值,參數為比較函數Map.prototype.max = function(compare){ var keys = this.keySet(); var maxKey = keys[0],maxValue = this.get(keys[0]); for(var i = 0;i < keys.length;i++){ if(compare(this.get(keys[i],maxValue))){ maxValue = this.get(keys[i]); maxKey = keys[i]; } } return [maxKey,maxValue];}//返回 map 中的 entrySet 對象Map.prototype.entrySet = function() { var array = new Array(); var keys = this.keySet(); for (var i = 0; i < keys.length; i++) { array.push(keys[i],this.container[keys[i]]); } return array;}

javascript實現Map結構

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.