Click to See Complete Forum and Search --> : array.length does not work properly?


Frenkieb
12-13-2005, 10:08 AM
Hi everybody,

first post, first question.

I have the following code:

<script type="text/javascript">
var arrTest = new Array();
arrTest["item_1"] = 1;
arrTest["item_2"] = 2;
alert(arrTest.length);
</script>

Now, I would say the length of the array is '2' but the alert says '0'. Why?

schephais
12-13-2005, 10:34 AM
The 'length' property is broken when using associative arrays. When you have an array with a variable length, it's generally better to use numeric indexes (arrTest[0] = "item_1", etc.)

If you need to use an associative array, you can loop through it like so:
var myLength = 0;
var arrTest = new Array();
arrTest["item_1"] = 1;
arrTest["item_2"] = 2;
for ( arrTestKey in arrTest ) {
myLength++;
}
alert ( myLength );This script loops through all the properties of the arrTest instance of the array object and adds 1 to myLength for each item.

Hope that helps.

Frenkieb
12-14-2005, 02:21 AM
That was definitely helpfull!