我有一个名为 arr = [[1,2],4] 的数组,以及用于访问数字的 for 循环。但我似乎无法添加最后一个数字。为什么不起作用?
let arr = [[1,2],4];
let total = 0;
for(let i = 0; i < arr.length; i++) {
for(let j = 0; j < arr[i].length; j++) {
total += arr[i][j];
}
}
console.log(arr.length) // returns length = 2
console.log(total); // returns total = 3
最佳答案
您的问题是您的数组不仅仅由数组组成,它还由单个数字和嵌套数组组成。因此,您的内部循环将无法循环数字 4
,因为它不是数组(因此它不会有 .length
属性)。
let arr = [[1,2],4];
// no issues-^ ^-- no `.length` property (inner for loop won't run)
对于这样的问题,您可以使用 recursive function ,当您遇到嵌套数组时,您可以调用函数来对该数组执行加法。
参见下面的示例(和代码注释):
function sumNums(arr) {
let total = 0;
for (let i = 0; i < arr.length; i++) {
if(Array.isArray(arr[i])) { // If current element (arr[i]) is an array, then call the sumNums function to sum it
total += sumNums(arr[i]);
} else {
total += arr[i]; // If it is not an array, then add the current number to the total
}
}
return total;
}
let arr = [[1,2],4];
console.log(sumNums(arr)); // 7
您还可以使用 .reduce()
进行递归调用如果您想采取这种方法:
const arr = [[1,2],4];
const result = arr.reduce(function sum(acc, v) {
return acc + (Array.isArray(v) ? v.reduce(sum, 0) : v);
}, 0);
console.log(result); // 7
关于javascript - 如何添加以下代码中的数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65387315/