Skip to content Skip to sidebar Skip to footer

Javascript Array Length Issue

I'm a bit lost with the following: When I do a console.log of two different arrays, one is giving me the actual length but not the other. Output of first array, with good length: [

Solution 1:

The second log message cannot output the length of the array because the values have been assigned to its properties as opposed to its indices, since there are no objects within the actual indices of the array the length property is 0. This occurs because arrays cannot contain non-numeric indices such as A,B,C,D.

So when you execute:

var arr= [];
arr["b"] = "test";

The code is actually assigning the string literal test to the b property of the arr array as opposed to an index. This is possible because arrays are objects in Javascript, so they may also have properties.

Solution 2:

The length of an Array object is simply its highest numeric index plus one. The second object has no numeric indices, so its length is 0.

If it were [ A: Object, B: Object, C: Object, 15: Object ], then its length would be 16. The value of length is not tied to the number of actual properties (4 in this case).

Post a Comment for "Javascript Array Length Issue"