Objects and Associative Arrays

by jeremyjones on March 20, 2011

  • Share
  • CevherShare
  • Share

The JavaScript Object is very versatile and useful. It works a little like the Object base type in Java and the associative array type like %hash from Perl, dict from Python or array from PHP, and is the best of both worlds. You can also use them for String to Object mapping.

You can initialize a JavaScript Object using shorthand syntax like this:


var Obj = new Object();

var Obj = {};

You can interchange item indexing and member selection. Both operations are equivalent.

Obj.a == Obj(‘a’);

The only type you can use for keys are Strings, so if you index an Object on another Object it converts the index to a string with the toString function.

Obj[1] == Obj[(1).toString()] == Obj['1'];

If you were used to the real hash mappings you might find in Python or Java, then you would need to find a JavaScript library to provide that functionality. There is no mechanism to overload item indexing in any JavaScript implementation and neither is there a default hash algorithm for objects. You will be able to find this functionality from a good library that will give you an associative array type with functions similar to getItem, setItem, hasItem and delItem, The library should also provide a general hash algorithm that returns good default hashes for every built-in type with polymorphic hash member functions.

Leave a Comment

Previous post:

Next post: