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:稀疏数组 vs. 密集数组.
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屋!