JavaScript数组非未定义元素计数 [英] Javascript array non undefined element count
问题描述
我使用 let arr = new Array(99999)
创建一个数组,但是我没有将其填充到 arr.length
是 99999
,我怎么知道我在其中有多少实际的,非 undefined
元素
I create an array with let arr = new Array(99999)
but I don't fill it up to arr.length
which is 99999
, how can I know how much actual, non undefined
elements do I have in this array?
有没有比查找第一个 undefined
更好的方法?
Is there a better way than to look for the first undefined
?
推荐答案
您可以使用 Array#forEach
,它会跳过稀疏元素。
You could use Array#forEach
, which skips sparse elements.
let array = new Array(99999),
count = 0;
array[30] = undefined;
array.forEach(_ => count++);
console.log(count);
let array = new Array(99999),
count = 0;
array[30] = undefined;
count = array.reduce(c => c + 1, 0);
console.log(count);
要过滤非稀疏/密集元素,可以使用一个回调,该回调为每个元素 true
返回。
For filtering non sparse/dense elements, you could use a callback which returns for every element true
.
也许此链接有助于稍微了解稀疏数组的机制: JavaScript:稀疏数组与密集数组。
Maybe this link helps a bit to understand the mechanic of a sparse array: JavaScript: sparse arrays vs. dense arrays.
let array = new Array(99999),
nonsparsed;
array[30] = undefined;
nonsparsed = array.filter(_ => true);
console.log(nonsparsed);
console.log(nonsparsed.length);
这篇关于JavaScript数组非未定义元素计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!