...

View Full Version : array.length weirdness



chump2877
12-22-2006, 08:08 PM
Maybe my brain is still in PHP mode, but why am I getting the following return values for array.length?:


<script type="text/javascript">

var x = new Array;
alert(x.length); // Returns "0"

x[12] = 12;
alert(x.length); // Returns "13" -- Why not 1?


var y = new Array;
alert(y.length); // Returns "0"

y['12'] = 12;
alert(y.length); // Returns "13" -- Why not 1?


var z = new Array;
alert(z.length); // Returns "0"

z['hi'] = 12;
alert(z.length); // Returns "0" -- Why not 1?


var a = new Array;
alert(a.length); // Returns "0"

a[12] = "blah";
alert(a.length); // Returns "13" -- Why not 1?

</script>

nikkiH
12-22-2006, 08:16 PM
Arrays in javascript are 0-based and the language is loosely typed. When you use a number as the index, it makes an array. When you use a string, it creates a hash and you must enumerate the elements instead. (for (p in z) alert(p); )

If you set an element to [12], you have 13 elements, 0-12.
If you set an element to [12], 0-11 are set to null for you.

chump2877
12-22-2006, 09:29 PM
thanks :thumbsup:



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum