[英]Why doesn't this recursive javascript function return the correct value
Why does this function return undefined
? 为什么此函数返回
undefined
?
The interior function returns the correct value. 内部函数返回正确的值。
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);
Change it to 更改为
return arguments.callee( s + y[0], y.slice(1))
Or just use reduce :-) : 或者只是使用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 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce
If what you said in the code's comment is true, this is what you need. 如果您在代码注释中所说的是正确的,那么这就是您所需要的。
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.
return (function (s, y) {
if (y instanceof Array && y.length !== 0) {
return arguments.callee(arguments.callee(s, y[0]), y.slice(1));
} else if (typeof y === 'number') {
return s + y;
} else {
return s;
}
})(0, i);
}
Output 产量
var x = [1, 2, 3, 4, 5];
console.log(arraySum(x));
x = [1, 2, [3, 4, 5]];
console.log(arraySum(x));
x = [1, "2", 2, [3, 4, 5]];
console.log(arraySum(x));
x = [1, "2", [2, [3, 4, 5]]];
console.log(arraySum(x));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.