JavaScript: Array Alternative


Instead of using a JavaScript array, sometimes you need to use a "properties list" instead. A properties list is really a name-value pair (a.k.a. key-value pair). Here's an example of how to declare it and different ways to reference objects in the list:

var x = {color:'blue' , height:100, width: 200};
for( y in x ) {
alert( y + "=" + x[y] );
}
alert( x.color );
alert( x["height"] );
alert( x['width'] );

I had to post this because I recently noticed different AJAX libraries (i.e. Prototype, moo.fx, Script.aculo.us) leveraging such code. It was foreign to me, so I thought others might benefit.

6 comments:

Drew LeSueur at: 1:04 PM said...
This comment has been removed by the author.
Drew LeSueur at: 1:09 PM said...

thank you ... I think it was this post that, a long time ago, might have helped influenced my thinking on JavaScript.

I remember referring back to it by searching for "leveraging such code" in google

Aaron Hursman at: 2:11 PM said...

hey, drew. wow, that is great to hear. you are right, it was posted a long time ago...when all the javascript libraries that we commonly use today were just gaining momentum. i'm glad you found it helpful. *this* is why we blog, eh? thanks for the comment. take care...

Jonathan at: 5:41 AM said...

Mistake, it should be...


alert( y + "=" + x[y] );

You missed the second "+"

Aaron Hursman at: 9:21 PM said...

Thanks, Jonathan. I've updated the post with the correction.

Anonymous at: 8:26 AM said...

YOU DON'T SAY

Post a Comment

Aaron Hursman
Aaron Hursman is a passionate user-advocate who is lucky enough to do what he loves for a living. As a user experience architect, he applies user-centered design principles and techniques including user research, persona development, information architecture, storyboards, wireframes, prototyping, visual design, graphic design, interaction design, and usability. Aaron has a background in web development, enterprise applications, and the social web. At nGame, he is applying his craft to design and build the next generation of enterprise software. Aaron is available as a speaker and author upon request.
Disclaimer: The information in this website is provided "as is" with no warranties, and confers no rights. This website does not represent the thoughts, intentions, plans or strategies of my employer. It is solely my own personal opinion. Inappropriate comments will be deleted at the authors discretion. All instructions and code samples (if any, ever) are provided "as is" without warranty of any kind, either express or implied.