Hash Table In Javascript
Solution 1:
Using the function above, you would do:
var myHash = new Hash('one',[1,10,5],'two', [2], 'three',[3,30,300]);
Of course, the following would also work:
var myHash = {}; // New object
myHash['one'] = [1,10,5];
myHash['two'] = [2];
myHash['three'] = [3, 30, 300];
since all objects in JavaScript are hash tables! It would, however, be harder to iterate over since using foreach(var item in object)
would also get you all its functions, etc., but that might be enough depending on your needs.
Solution 2:
If all you want to do is store some static values in a lookup table, you can use an Object Literal (the same format used by JSON) to do it compactly:
vartable= { one: [1,10,5], two: [2], three: [3, 30, 300] }
And then access them using JavaScript's associative array syntax:
alert(table['one']); // Will alert with [1,10,5]
alert(table['one'][1]); // Will alert with 10
Solution 3:
You could use my JavaScript hash table implementation, jshashtable. It allows any object to be used as a key, not just strings.
Solution 4:
The Javascript interpreter natively stores objects in a hash table. If you're worried about contamination from the prototype chain, you can always do something like this:
// Simple ECMA5 hash tableHash = function(oSource){
for(sKey in oSource) if(Object.prototype.hasOwnProperty.call(oSource, sKey)) this[sKey] = oSource[sKey];
};
Hash.prototype = Object.create(null);
var oHash = newHash({foo: 'bar'});
oHash.foo === 'bar'; // true
oHash['foo'] === 'bar'; // true
oHash['meow'] = 'another prop'; // true
oHash.hasOwnProperty === undefined; // trueObject.keys(oHash); // ['foo', 'meow']
oHash instanceofHash; // true
Post a Comment for "Hash Table In Javascript"