本文為大家介紹下使用js實現的map方法,具體示例如下,喜歡的朋友可以了解下
代碼如下: /** * * 描述:js實現的map方法 * @returns {Map} */ function Map(){ var struct = function(key, value) { this.key = key; this.value = value; }; // 添加map鍵值對 var put = function(key, value){ for (var i = 0; i < this.arr.length; i++) { if ( this.arr[i].key === key ) { this.arr[i].value = value; return; } }; this.arr[this.arr.length] = new struct(key, value); }; // 根據key獲取value var get = function(key) { for (var i = 0; i < this.arr.length; i++) { if ( this.arr[i].key === key ) { return this.arr[i].value; } } return null; }; // 根據key刪除 var remove = function(key) { var v; for (var i = 0; i < this.arr.length; i++) { v = this.arr.pop(); if ( v.key === key ) { continue; } this.arr.unshift(v); } }; // 獲取map鍵值對個數 var size = function() { return this.arr.length; }; // 判斷map是否為空 var isEmpty = function() { return this.arr.length <= 0; }; this.arr = new Array(); this.get = get; this.put = put; this.remove = remove; this.size = size; this.isEmpty = isEmpty; } 使用方法和java中Map類同 代碼如下: <script type="text/javascript"> var map=new Map(); map.put("num",1); map.put("ss","wss"); alert(map.size()); alert(map.get("num")); paraArr.remove("num"); alert(map.size()); alert(map.get("num")); </script>