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> 

我该怎么做?

使用上面的函数,你可以这样做:

 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)也可以得到所有的function等等,所以迭代起来会比较困难,但根据您的需要,这可能已经足够了。

如果你所要做的只是在查找表中存储一些静态值,你可以使用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 

你可以使用我的JavaScript哈希表实现, jshashtable 。 它允许任何对象被用作关键字,而不仅仅是string。

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