我有一个问题,我必须对数组中的数字求和,我所做的工作正常,但在一种情况下除外:
sum([1, [2, 3, [4, 5], 6], 7, [8, 9]]) === 45
function sum(arr) {
var arrsum = 0;
for (var index = 0; index < arr.length; index++) {
if (!isNaN(arr[index])) {
arrsum += arr[index];
}
}
return arrsum;
}
这个结果是8,你知道怎么只改函数就变成45了吗? 非常感谢。
最佳答案
关键是当在第一个数组中找到另一个数组时,使您的函数递归。
console.log(sum([1, [2, 3, [4, 5], 6], 7, [8, 9]])); // === 45
function sum(arr) {
var result = 0; // answer will go here
// This function will do the looping over all arrays
function loop(ary){
arr.forEach(function(element){
// If the item is a number...
if(typeof element === "number"){
result += element; // Add it to the total
} else if(typeof element === "object"){
// If it's an object (Array in this case), run the function recusively
result += sum(element);
}
});
}
loop(arr);
return result;
}
关于javascript - 在特定情况下,数组中数字的总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48631648/