home   articles   tags   browse code   

Javascript - Objects as Associative Arrays


 

In Javascript, every object is also an associative array of keys and values. Each 'variable' or 'attributes' of the object is a key value pair, where the name of the variable is the 'key' and the value of the variable is the 'value' of the kv pair. This means that you can iterate through an object's 'attributes'.

Your own object:
function assoc1()
{
    var m = new Object();
    m["has_cpu"] ="Y";
    m.has_memory ="N";
    for( var key in m )
    {
        alert( key+":"+m[key] );
    }
}


An existing html element:
function assoc2()
{
    var e = document.getElementById('div_id');
    for( var key in e )
    {
        alert( key+":"+e[key] );
    }
}


This is especially useful for debugging, and building cross-browser web applications, because different browsers pre-define different attributes and methods in their javascript implementations.

The body element:
function assoc3()
{
    var b = document.body;
    for( var key in b )
    {
        console.log( key+":"+b[key] );
    }
}

The console.log function is defined in Firebug, and an excellent debugging tool. It is important to use something like firebug when debugging instead of just 'alert' boxes, because sometimes you would have to click [OK] on 90 alert boxes, like if you output predefined objects like 'body' as associative arrays.






 

 


 

 



Related Articles
 


home  |  privacy policy  |  terms of use  |  contact  


©2012, Zedwood.com

zedwood.com is a participant in the Amazon Services LLC Associates Program, an affiliate advertising program designed to provide a means for sites to earn advertising fees by advertising and linking to amazon.com