为什么在else语句中randomHull()之前需要“返回”?

此函数的目标是返回3到6之间的值。我知道有一种更简单的方法可以执行此操作,但是我只是想了解此选项的工作方式/原因。

以下函数有效,但仅当您在else语句中使用return时才有效。如果您不使用“ return randomHull()”,而是仅放置“ randomHull()”,则如果第一次尝试不在该范围内,它将返回未定义。

我最初的理解是不需要返回,因为只有在if语句为true时才存储值,否则它将再次运行randomHull()直到它通过if语句并返回范围内的值。

为什么在else语句中randomHull()之前需要“返回”?

const randomHull = () => {
     let alienHull = Math.ceil(Math.random() * 6);
     if (alienHull >= 3) {
        return alienHull;
     } else {
        return randomHull();
     }

}

console.log(randomHull());
评论
  • 按到角落
    按到角落 回复

    这是一个递归函数。

    https://en.wikipedia.org/wiki/Recursion_(computer_science)

    It works because it calls itself again until it meets the condition in the if. Every execution will be a step closer to >= 3 and eventually hit the case in the if.

  • siusto
    siusto 回复

    假设它在第二次尝试中找到了匹配项。

    The first attempt hits the else branch, then calls the randomHull function.

    The return value from that is passed back to the calling function (the first call to randomHull). Then nothing would be done with it (it isn't returned because you took return out, it isn't stored in a variable because you don't do that either, etc).

    The first call to randomHull contains. It hits the } to end the else block. Then it hits the } to end the function. Since it reached the end of the function without a return statement, it returns undefined.