递归函数的返回值为“未定义”

22
每当我执行这个片段时,return之前的console.log会返回一个数组,该数组包含20次值为23的元素。 然而console.log(Check(users, 0, 20));只返回'undefined'。
我做错了什么?
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;
    }
}

2
if 代码块中没有 return 语句意味着返回值为 undefined。如果您在函数末尾放置一个 return 语句并根据 if 语句设置要返回的值,则可能更容易进行维护。 - Ian
这个回答是否解决了您的问题?从函数返回undefined - outis
1个回答

44
您忘记在递归进入点返回结果。
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;
    }
} 

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


我尽可能简化了函数,以免分散注意力。非常感谢。 - Hedge

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接