【问题标题】:Return value of recursive function is 'undefined'递归函数的返回值为“未定义”
【发布时间】:2013-07-05 21:34:54
【问题描述】:

每当我执行这个 sn-p 时,console.log 在 return 之前返回的数组是 23 的 20 倍。 但是 console.log(Check(users, 0, 20));仅返回“未定义”。

我做错了什么?

var users = [23, 23, 23, 23, 23, 23, 23, 23, 23, 23];
console.log(Check(users, 0, 20));

function Check(ids, counter, limit){
    ids.push(23);

    // Recursion
    if (counter+1 < limit){
        Check(ids, counter+1, limit);
    }
    else {
        console.log(ids);
        return ids;
    }
}

【问题讨论】:

  • return 块中的无 return 语句表示 undefined。如果您在函数末尾放置一个return 语句并根据if 语句设置要返回的值,可能会更容易维护
  • 这能回答你的问题吗? undefined returned from function

标签: javascript recursion return


【解决方案1】:

您忘记从输入 recursion 的位置返回结果。

var users = [23, 23, 23, 23, 23, 23, 23, 23, 23, 23];
console.log(Check(users, 0, 20));

function Check(ids, counter, limit){
    ids.push(23);

    // Recursion
    if (counter+1 < limit){
        return Check(ids, counter+1, limit); // return here!
    }
    else {
        console.log(ids);
        return ids;
    }
} 

但是返回值似乎没用,因为你的函数也改变了初始数组。

【讨论】:

  • 我尽可能地简化了功能,以免分散实际问题的注意力。非常感谢。
猜你喜欢
  • 1970-01-01
  • 2012-09-26
相关资源
最近更新 更多