ven*_*lam 41 javascript hashtable
我在JavaScript中使用哈希表,我想在哈希表中显示以下值
one -[1,10,5]
two -[2]
three -[3, 30, 300, etc.]
Run Code Online (Sandbox Code Playgroud)
我找到了以下代码.它适用于以下数据.
one -[1]
two -[2]
three-[3]
Run Code Online (Sandbox Code Playgroud)
如何将一个[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>
Run Code Online (Sandbox Code Playgroud)
我该怎么做?
ror*_*ryf 74
使用上面的函数,你会做:
var myHash = new Hash('one',[1,10,5],'two', [2], 'three',[3,30,300]);
Run Code Online (Sandbox Code Playgroud)
当然,以下也可以:
var myHash = {}; // New object
myHash['one'] = [1,10,5];
myHash['two'] = [2];
myHash['three'] = [3, 30, 300];
Run Code Online (Sandbox Code Playgroud)
因为JavaScript中的所有对象都是哈希表!然而,迭代会更难,因为使用foreach(var item in object)也可以获得所有功能等,但这可能足以取决于您的需求.
Sha*_*mer 32
如果您只想在查找表中存储一些静态值,则可以使用Object Literal(JSON使用的格式相同)来紧凑地执行:
var table = { one: [1,10,5], two: [2], three: [3, 30, 300] }
Run Code Online (Sandbox Code Playgroud)
然后使用JavaScript的关联数组语法访问它们:
alert(table['one']); // Will alert with [1,10,5]
alert(table['one'][1]); // Will alert with 10
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)