简体   繁体   中英

Wrong representation of JavaScript Array Length

If I have an array in JavaScript, say:

var a = [1, 2, 3];
var b = ["Praveen", "Kumar", "Stack", "Overflow"];

If I get the lengths of the above arrays by:

a.length;
b.length;

I get the correct values. ie,

a.length;  // 3
b.length;  // 4

But, if I create another array, where I set my indices like:

c = [];
c[5] = "Five";
c[10] = "Ten";

And then if I query the length, it shows me 11 .

c.length  // 11

Is this wrong? Or is this way JavaScript interprets arrays? Please guide.

The .length is defined to be one greater than the value of the largest numeric index. (It's not just "numeric"; it's 32-bit integer values, but basically numbered properties.)

Conversely, setting the .length property to some numeric value (say, 6 in your example) has the effect of deleting properties whose property name is a number greater than or equal to the value you set it to.

The effect of

var c = [];
c[10] = "foo";

is that c will look like this:

c[0] === undefined
c[1] === undefined
c[2] === undefined
c[3] === undefined
c[4] === undefined
c[5] === undefined
c[6] === undefined
c[7] === undefined
c[8] === undefined
c[9] === undefined
c[10] === "foo"

Having elements 0 through 10, the length of the array is therefore 11.

It's correct. The length depends on the highest index used, not the number of actual items in the array.

Creating an array like this:

c = [];
c[5] = "Five";
c[10] = "Ten";

Has the exact same effect as this:

c = [,,,,,"Five",,,,,"Ten"];

Although the array only has two items, the length is 11 as the highest index used is 10.

The string representation of the array will be [undefined, undefined, undefined, undefined, undefined, "Five", undefined, undefined, undefined, undefined, "Ten"] as it uses the length and shows a value for all indexes up to that.

If you loop the properties in the array, you will only get indexes of the actual items:

for (n in c) console.log(n);

Output:

5
10

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM