Nov 28, 2008

Prototype Hash Processing

Hash can be thought of as an associative array binding unique keys to values. Only difference is that you can use any string as an index instead of just using a number as index.
Creating a hash:
There are two ways to construct a Hash instance:
* Use JavaScript keyword new
* Using Prototype Utility function $H
To create an empty hash you call any of the constructor methods without arguments, too.

Following is the example showing how to create hash, setting values and getting values in simple way:
// Creating Hash
var myhash = new Hash();
var yourhash = new Hash( {fruit: 'apple'} );
var hishash = $H( {drink: 'pepsi'} );

// Set values in terms of key and values.
myhash.set('name', 'Bob');

// Get value of key 'name' as follows.
myhash.get('name');
yourhash.get('fruit');
hishash.get('drink');

// Unset a key & value
myhash.unset('name');
yourhash.unset('fruit');
hishash.unset('drink');

Methods

Description

clone()

Returns a clone of hash.

each()

Iterates over the name/value pairs in the hash.

get()

Returns the value of the hash's key property.

inspect()

Returns the debug-oriented string representation of the hash.

keys()

Provides an Array of keys (that is, property names) for the hash.

merge()

Merges object to hash and returns the result of that merge.

remove()

Removes keys from a hash and returns their values. This method has been deprecated in version 1.6.

set()

Sets the hash's key property to value and returns value.

toJSON()

Returns a JSON string.

toObject()

Returns a cloned, vanilla object.

toQueryString()

Turns a hash into its URL-encoded query string representation.

unset()

Deletes the hash's key property and returns its value.

update()

Updates hash with the key/value pairs of object. The original hash will be modified.

values()

Collect the values of a hash and returns them in an array.

No comments: