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

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

最佳答案

改成

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/

相关文章:

javascript - 不可变js的递归分组

javascript - 递归打印字符串的所有排列(Javascript)

sql-server - SQL 查询,例如带有 OR 条件的 GROUP BY

javascript - 在不删除关联事件的情况下从节点中删除元素?

javascript - 有没有办法指定 date.js 的输入格式?

javascript - 递归函数无法正常工作

haskell - 删除列表中满足条件的第一个值

javascript - 在 JSON 中使用动态值

Javascript:无法通过 Ajax 调用访问对象属性

javascript - 如何将匿名帐户转换为永久帐户