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

时间:2013-10-06 02:22:12

标签: javascript recursion

为什么此函数会返回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);

2 个答案:

答案 0 :(得分:1)

将其更改为

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

答案 1 :(得分:0)

如果您在代码评论中所说的内容属实,那么这就是您所需要的。

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);
}

<强>输出

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));