gpt4 book ai didi

javascript - 为什么这个递归 javascript 函数不返回正确的值

转载 作者:行者123 更新时间:2023-11-30 05:43:49 28 4
gpt4 key购买 nike

为什么这个函数返回undefined

内部函数返回正确的值。

function arraySum(i) {

// i will be an array, containing integers, strings and/or arrays like itself.
// Sum all the integers you find, anywhere in the nest of arrays.

(function (s, y) {
if (!y || y.length < 1) {
//console.log(s);
// s is the correct value
return s;
} else {
arguments.callee(s + y[0], y.slice(1));
}
})(0, i);
}

var x = [1, 2, 3, 4, 5];
arraySum(x);

最佳答案

改成

return arguments.callee( s + y[0], y.slice(1))

或者只使用 reduce :-) :

[1,2,3,4].reduce( function(sum, x) { return sum + x; }, 0 );

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce

关于javascript - 为什么这个递归 javascript 函数不返回正确的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19204761/

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