2009-01-19 91 views
40

我使用的是哈希表中的JavaScript,我想表明在哈希表哈希表中的JavaScript

one -[1,10,5] 
two -[2] 
three -[3, 30, 300, etc.] 

我發現下面的代碼下面的值。它適用於以下數據。

one -[1] 
    two -[2] 
    three-[3] 

如何將一個[1,2]值分配給哈希表,以及如何訪問它?

<script type="text/javascript"> 
    function Hash() 
    { 
     this.length = 0; 
     this.items = new Array(); 
     for (var i = 0; i < arguments.length; i += 2) { 
      if (typeof(arguments[i + 1]) != 'undefined') { 
       this.items[arguments[i]] = arguments[i + 1]; 
       this.length++; 
      } 
     } 

     this.removeItem = function(in_key) 
     { 
      var tmp_value; 
      if (typeof(this.items[in_key]) != 'undefined') { 
       this.length--; 
       var tmp_value = this.items[in_key]; 
       delete this.items[in_key]; 
      } 
      return tmp_value; 
     } 

     this.getItem = function(in_key) { 
      return this.items[in_key]; 
     } 

     this.setItem = function(in_key, in_value) 
     { 
      if (typeof(in_value) != 'undefined') { 
       if (typeof(this.items[in_key]) == 'undefined') { 
        this.length++; 
       } 

       this.items[in_key] = in_value; 
      } 
      return in_value; 
     } 

     this.hasItem = function(in_key) 
     { 
      return typeof(this.items[in_key]) != 'undefined'; 
     } 
    } 

    var myHash = new Hash('one',1,'two', 2, 'three',3); 

    for (var i in myHash.items) { 
     alert('key is: ' + i + ', value is: ' + myHash.items[i]); 
    } 
</script> 

我該怎麼做?

回答

71

用上面的功能,你會怎麼做:

var myHash = new Hash('one',[1,10,5],'two', [2], 'three',[3,30,300]); 

當然,下面也將工作:

var myHash = {}; // New object 
myHash['one'] = [1,10,5]; 
myHash['two'] = [2]; 
myHash['three'] = [3, 30, 300]; 

因爲在JavaScript中的所有對象都是哈希表!但是,由於使用foreach(var item in object)也可以獲得所有功能等,但它會更難以迭代,但根據您的需要,這可能已足夠。

+21

keys = Object.keys(myHash)將給出一個鍵的數組,所以在這種情況下它會返回['一二三']。然後你可以使用for(var i = 0; i zupa 2013-01-16 15:17:19

+0

我在javascript中找不到哈希。 (哈希值沒有定義。)你能否提供鏈接 – jforjs 2016-10-18 08:36:11

32

如果你想要做的是存儲在一個查找表中的一些靜態值,你可以使用一個Object Literal(同樣由JSON使用格式)做緊湊:

var table = { one: [1,10,5], two: [2], three: [3, 30, 300] } 

,然後使用訪問它們JavaScript的關聯數組語法:

alert(table['one']); // Will alert with [1,10,5] 
alert(table['one'][1]); // Will alert with 10 
8

您可以使用我的JavaScript哈希表實現,jshashtable。它允許任何對象被用作關鍵字,而不僅僅是字符串。

2

Javascript解釋器本身將對象存儲在散列表中。如果你擔心原型鏈受到污染,你總是可以這樣做:

// Simple ECMA5 hash table 
Hash = function(oSource){ 
    for(sKey in oSource) if(Object.prototype.hasOwnProperty.call(oSource, sKey)) this[sKey] = oSource[sKey]; 
}; 
Hash.prototype = Object.create(null); 

var oHash = new Hash({foo: 'bar'}); 
oHash.foo === 'bar'; // true 
oHash['foo'] === 'bar'; // true 
oHash['meow'] = 'another prop'; // true 
oHash.hasOwnProperty === undefined; // true 
Object.keys(oHash); // ['foo', 'meow'] 
oHash instanceof Hash; // true