数组的 .length 属性将返回数组中元素的数量。例如,下面的数组包含 2 个元素:
[1, [2, 3]] // 2 个元素,数字 1 和数组 [2, 3] 假设我们想知道嵌套数组中非嵌套项的总数。在上述情况下,[1, [2, 3]] 包含 3 个非嵌套项,1、2 和 3。
例子
getLength([1, [2, 3]]) ? 3
getLength([1, [2, [3, 4]]]) ? 4
getLength([1, [2, [3, [4, [5, 6]]]]]) ? 6
Run Code Online (Sandbox Code Playgroud)
Nic*_*ons 17
您可以使用展平数组.flat(Infinity),然后获取长度。.flat()与参数一起使用Infinity将把嵌套数组中的所有元素连接到一个外部数组中,允许您计算元素的数量:
const getLength = arr => arr.flat(Infinity).length;
console.log(getLength([1, [2, 3]])) // ? 3
console.log(getLength([1, [2, [3, 4]]])) // ? 4
console.log(getLength([1, [2, [3, [4, [5, 6]]]]])) // ? 6Run Code Online (Sandbox Code Playgroud)
您可以在每个数组上使用 reduce ,如下所示:
function getLength(arr){
return arr.reduce(function fn(acc, item) {
if(Array.isArray(item)) return item.reduce(fn);
return acc + 1;
}, 0);
}
console.log(getLength([1, [2, 3]]))
console.log(getLength([1, [2, [3, 4]]]))
console.log(getLength([1, [2, [3, [4, [5, 6]]]]]))Run Code Online (Sandbox Code Playgroud)