简体   繁体   English

JavaScript数组长度的错误表示

[英]Wrong representation of JavaScript Array Length

If I have an array in JavaScript, say: 如果我在JavaScript中有一个数组,请说:

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 . 然后如果我查询长度,它会显示我11

c.length  // 11

Is this wrong? 这是错的吗? Or is this way JavaScript interprets arrays? 或者这样JavaScript解释数组? Please guide. 请指导。

The .length is defined to be one greater than the value of the largest numeric index. .length被定义为大于最大数字索引的值。 (It's not just "numeric"; it's 32-bit integer values, but basically numbered properties.) (它不仅仅是“数字”;它是32位整数值,但基本上是编号属性。)

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. 相反, .length属性设置为某个数值(例如,示例中为6 )会删除属性名称大于或等于您设置的值的属性。

The effect of 的效果

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

is that c will look like this: c将如下所示:

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. 具有元素0到10,因此数组的长度为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. 虽然数组只有两个项目,但长度为11,因为使用的最高索引是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. 数组的字符串表示形式将是[undefined, undefined, undefined, undefined, undefined, "Five", undefined, undefined, undefined, undefined, "Ten"]因为它使用长度并显示所有索引的值,直到。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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