Wednesday, March 18, 2009

Multidimensional hashes in javascript

When i first started out with javascript i had no idea how to make a multidimensional array or a hash. Then, for a while i did not know how to use it properly after creating it. Now that i _think_ i know what i am doing i want share this very useful knowledge with the world.

First things first. A hash is the corner stone of all javascript objects and it is easy to create:

Each of the above is a perfectly valid way to create and access a hash. Quotes around the name allows you to use reserved words as the name, such as "function".

One thing to note here, is that the name must be either a string or a number, if its a number, you are better off using an array (if all your other keys are numbers too). This means that the name cannot be an object.

Now lets create a hash with more than one dimension. The function below is used to both init and add to a 3D hash.

We make sure not to access any elements that are undefined / not an object.

Now all we have left is a function to get values from our hash. This is not as straight forward as it may seem
The first statement is wrong, because if any of the 3 values passed in does not exist in the hash, you will try to access a property of undefined, causing an error. The second statement makes sure that each dimension exists before trying to access it, and finally returns either the value you want, or undefined.

Thats it!

3 comments:

  1. Thanks!

    Nice site!

    By the way, it is very difficult to post (unable to see the captcha answer box unless I "tab" there - window wont scroll, FYI)

    ReplyDelete
  2. @anon: thanks for letting me know, i fixed the template =)

    ReplyDelete
  3. Fantastic, thanks! Will come in handy for building reports.

    ReplyDelete