2

この関数が を返すのはなぜundefinedですか?

interior 関数は正しい値を返します。

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

または、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

于 2013-10-06T02:27:05.647 に答える