gpt4 book ai didi

javascript - 在特定情况下,数组中数字的总和

转载 作者:行者123 更新时间:2023-11-30 09:27:17 25 4
gpt4 key购买 nike

我有一个问题,我必须对数组中的数字求和,我所做的工作正常,但在一种情况下除外:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com