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;  
    }  

 

<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> 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM