28 May 2009

Hash in JavaScript

Hashing in JavaScript is interesting and a bit different. String indexing of array is actually hashing. Let me explain. You can use array in following way

var myArray = new Array();

myArray["MyKey"] = "My Value";


What actually happens here is, an attribute named "MyKey" is created in the object myArray. The interesting point is- you can access the attribute like myArray.MyKey. And this trick acts as hash if you index the array with key and put the value accordingly.

You can access all the keys like the following.

for(var key in myArray)

{

alert(key);

}

It is used to get all items in a hash.

A Hash class is given below.

function Hash()

{

this._items = new Array();

this.setItem = function(strKey, value)

{

if (typeof(value) != 'undefined')

this._items[strKey] = value;

};

this.getItem = function(strKey)

{

return this._items[strKey];

};

this.removeItem = function(strKey)

{

if (typeof(this._items[strKey]) != 'undefined')

delete this._items[strKey];

};

this.hasItem = function(strKey)

{

return typeof(this._items[strKey]) != 'undefined';

};

this.getAllItems = function()

{

var arrItems = new Array();

for(var k in this._items)

{

var m = this.getItem(k);

arrItems.push(m);

}

return arrItems;

}

this.clear = function()

{

delete this._items;

this._items = new Array();

};

}

0 Comments:

 

© 2007 t!ps n tr!cks: Hash in JavaScript



Template unik dari rohman


---[[ Skip to top ]]---