Array.length 给出的长度不正确 [英] Array.length gives incorrect length
问题描述
如果我有一个数组,其对象作为索引处的值,例如:
If I have an array having object as values at the indices like:
var a = [];
a[21] = {};
a[90] = {};
a[13] = {};
alert(a.length); // outputs 91
我找到了一种获取实际长度的解决方法:
I have found a workaround to get the actual length:
function getLength(arr) {
return Object.keys(arr).length;
}
var a = [];
a[21] = {};
a[90] = {};
a[13] = {};
alert(getLength(a));
但是,当对象以随机索引存储时,为什么 JS 给出的长度不正确? 它只是将数组中找到的最大索引加 1.与上面的示例一样,90 是最大的索引.它只是加 1 并给出 91 作为输出.演示
But, why does JS gives incorrect length when objects are stored at random indices? It just adds 1 to the largest index found on an array. Like in the above example, 90 was the largest index. It just adds 1 and gives 91 as output. Demonstration
推荐答案
那是因为 length
为您提供数组中可用的下一个 index
.
That's because length
gives you the next index
available in the array.
数组长度
如果传递给 Array 构造函数的唯一参数是 0 到 2^32-1(含)之间的整数,则返回一个长度设置为该数字的新 JavaScript 数组.
If the only argument passed to the Array constructor is an integer between 0 and 2^32-1 (inclusive), this returns a new JavaScript array with length set to that number.
因为除了 21、90、13 之外,您没有在其他键中插入任何元素,所以所有剩余的索引都包含 undefined
.演示
Because you don't have inserted any element in the other keys than 21, 90, 13, all the remaining indexes contains undefined
. DEMO
获取数组中元素的实际数量:
To get actual number of elements in the array:
var a = [];
a[21] = {};
a[90] = {};
a[13] = {};
var len = 0;
for (var i = 0; i < a.length; i++) {
if (a[i] !== undefined) {
len++;
}
}
document.write(len);
较短的版本
var a = [];
a[21] = {};
a[90] = {};
a[13] = {};
for (var i = 0, len = 0; i < a.length; i++, a[i] !== undefined && len++);
document.write(len);
编辑
如果数组包含大量元素,循环获取其长度不是最佳选择.
If the array contains large number of elements, looping to get its length is not the best choice.
正如您在问题中提到的,Object.keys(arr).length
在这种情况下是最佳解决方案,考虑到您没有任何添加到该数组上的属性.否则,length
将不会是您所期望的.(感谢 @RobG)
As you've mentioned in the question, Object.keys(arr).length
is the best solution in this case, considering that you don't have any properties added on that array. Otherwise, the length
will not be what you might be expecting.(Thanks To @RobG)
这篇关于Array.length 给出的长度不正确的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!