2

为什么这个函数返回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);
4

2 回答 2

1

将其更改为

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

或者只是使用减少:-):

[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

于 2013-10-06T02:27:05.647 回答
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));
于 2013-10-06T02:59:33.880 回答