jQuery: associative arrays

Unlike PHP, JavaScript has no true notion of associative arrays. A quick-and-dirty way to get this kind of result is as follows:

var assocArray = new Array();
assocArray['CSS'] = 'A stylesheet language.';
assocArray['DOM'] = 'An interface for web documents.';
assocArray['HTML5'] = 'The future of HTML.';

A more elegant solution is to use object literals:

    var assocArrObj = {
        CSS: 'A stylesheet language.',
        DOM: 'An interface for web documents.',
        HTML5: 'The future of HTML.'

jQuery allows us to iterate through this kind of objects with the $.each() method:

    $.each(assocArrObj, function(key) {
        alert(key + ' ' + assocArrObj[key]);


The above code will alert each key followed by its value. As you can see, this is a more elegant way than the usual for...in loop.

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

Leave a Reply

Note: Only a member of this blog may post a comment.