Associative Arrays (Dictionary-Style) in JavaScript with Integer Values

What do you think the last 3 alert dialogs will show? Those of you who say 1, 0 and NaN are absolutely right.

Take a look at this simple code with my comments:

JS
function TestAssociativeArray() {
    var myArray = new Array();
    //-An item can be created using either array notation ["a"] or object notation .a
    myArray.a = 0;
    //-If the item holds a number, you can easily increment it
    myArray["a"]++;
    //-To check whether an item exists in the array, compare it with undefined
    if (myArray.b == undefined) {
        //-Initialize the array item using object notation. It can be any number
        myArray.b = 0;
    }
    //-If the item is not initialized first and we try to increment it, NaN is stored as the result
    myArray["c"]++;

    alert(myArray.a);
    alert(myArray["b"]);
    alert(myArray.c);
}

I’m starting to really like JavaScript :D. I didn’t expect JS to handle this right out of the box.

Categories

Leave a Reply