Saturday, October 2, 2010

Javascript is Crazy

I have found out that javascript has some things that you have to be aware of or errors can creep into your code and you wouldn't know why.

I found this page that shows some weirdness of Javascript.
http://www.ozzu.com/programming-forum/javascript-get-array-key-name-t43467.html

There is no real associative array in Javascript. In most languages such as PHP you can do this.
$person = array();
$person['eyes'] = 'blue';
$person['hair'] = 'brown';
$person[1] = 'a number';
echo count($person); //returns 2

$person['length'] = '1 foot';
echo count($person); //returns 3

In Javascript here is what I found out.
You can try the same thing but it won't work right.
One reason is you have to get to Javascript associative arrays by its properties. Normally if you use numbers instead of words in the array keys you can go through the array with a for loop using:
for(x=0;x < person.length;x++){alert(x);}
When you use that with associative arrays it will show a length of 0 in the array. But you can loop through the array using for(x in person){alert(x);}

Here is the example for Javascript:
person = new Array();
person[0] = 'a number';
person['eyes'] = 'blue';
person['hair'] = 'brown';

alert(person.length); //returns 1 It only sees the associative array
alert(person.toString());

person['length'] = 99;
alert(person.length); //returns 99 this is the weird part
alert(person.hair); // returns brown

And if you use a string like 'one foot' for the length is will create an error since it is only expecting a number here. The length property is set by using x = new Array(99); and this is for making the array resized so if you made 3 items in the array then set the array to a size of 2 with:
x['length'] = 2;
You will notice that you won't be able to get at the 3rd array since the length has been truncated.

To go through the array above in Javascript you need to use the
for(x in person){
alert(x);
}

This is the way to get at the associative properties of the array.