数组上的.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
答案 0 :(得分:16)
您可以使用.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]]]]])) // ➞ 6
答案 1 :(得分:5)
您可以在每个数组上使用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]]]]]))
答案 2 :(得分:4)
递归计算不递归到的元素:
function getLength(a) {
let count = 0;
for (const value of a) {
if (Array.isArray(value)) {
// Recurse
count += getLength(value);
} else {
// Count
++count;
}
}
return count;
}
实时示例:
function getLength(a) {
let count = 0;
for (const value of a) {
if (Array.isArray(value)) {
count += getLength(value);
} else {
++count;
}
}
return count;
}
console.log(getLength([1, [2, 3]]));
console.log(getLength([1, [2, [3, 4]]]));
console.log(getLength([1, [2, [3, [4, [5, 6]]]]]));
答案 3 :(得分:2)
您可以只添加一个或多个嵌套数组的长度。
function getLength(array) {
let count = 0;
for (const item of array) count += !Array.isArray(item) || getLength(item);
return count;
}
console.log(getLength([1, [2, 3]]));
console.log(getLength([1, [2, [3, 4]]]));
console.log(getLength([1, [2, [3, [4, [5, 6]]]]]));