DevChunks

Objects and Associative Arrays

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 is 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, you would need to find a JavaScript library to provide that functionality.

There is currently 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 sound 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.

Share:

Leave a Reply

Your email address will not be published.

More Posts

How to use PHP Type Declarations

PHP has developed into a more strictly typed language in recent years. Type Declarations help with that and are a fairly new addition to PHP,

Iteration

If you have come to JavaScript from a background in Java or C, then you will like the variation on the for loop. It is

Context Object Manipulation

One of the key concepts of JavaScript is the keyword this, which signifies the JavaScript context object. If you write an inner function, you can access

Polymorphic Functions

It is possible to define multiple functions with the same name in JavaScript, and the last one of those that you define will be the