您可以使用压平未知深度的数组
array.flat(Infinity).length
您可以自己计算元素,但使用循环和堆栈而无需递归(没有最大调用堆栈大小错误),这将更有效,因为您不创建新数组:
console.log(countNestedArrayItems([1,2,3,4,[5,6],[[[[7,8]]]]]));
function countNestedArrayItems(arr) {
let count = 0;
const path = [];
for (let i = 0; i < arr.length; i++) {
const item = arr[i];
if (Array.isArray(item)) {
path.push(arr, i);
i = -1;
arr = item;
continue;
}
count++;
while(i === arr.length - 1 && path.length) i = path.pop(), arr = path.pop();
}
return count;
}
以及一个基准:
` Chrome/124
-----------------------------------------------------------------------------------
> n=6 | n=60 | n=600 | n=6000
count â 1.00x x1m 116 | â 1.00x x100k 94 | â 1.00x x100k 927 | â 1.00x x10k 860
flat() 1.75x x1m 203 | 2.17x x100k 204 | 2.29x x10k 212 | 2.60x x1k 224
-----------------------------------------------------------------------------------
https://github.com/silentmantra/benchmark `
const $chunk = [1,2,3,4,[5,6],[[[[7,8,[1,2,3,4,[5,6],[[[[7,8]]]]]]]]]];
const $input = [];
function countNestedArrayItems(arr) {
let count = 0;
const path = [];
for (let i = 0; i < arr.length; i++) {
const item = arr[i];
if (Array.isArray(item)) {
path.push(arr, i);
i = -1;
arr = item;
continue;
}
count++;
while(i === arr.length - 1 && path.length) i = path.pop(), arr = path.pop();
}
return count;
}
// @benchmark count
countNestedArrayItems($input);
// @benchmark flat()
$input.flat(Infinity).length;
/*@skip*/ fetch('https://cdn.jsdelivr.net/gh/silentmantra/benchmark/loader.js').then(r => r.text().then(eval));