Javascript array length incorrect on array of objects

Posted by Serenti on Stack Overflow See other posts from Stack Overflow or by Serenti
Published on 2010-03-27T08:52:46Z Indexed on 2010/03/27 9:03 UTC
Read the original article Hit count: 225

Filed under:
|
|

Could someone explain this (strange) behavior? Why is the length in the first example 3 and not 2, and most importantly, why is the length in the second example 0? As long as the keys are numerical, length works. When they are not, length is 0. How can I get the correct length from the second example? Thank you.

a = [];
a["1"] = {"string1":"string","string2":"string"};
a["2"] = {"string1":"string","string2":"string"};
alert(a.length); // returns 3

b = [];
b["key1"] = {"string1":"string","string2":"string"};
b["key2"] = {"string1":"string","string2":"string"};
alert(b.length); // returns 0

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about array