如何在变量 JavaScript 中保存递归函数的返回值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33513358/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 16:34:23  来源:igfitidea点击:

How to save the return value of a recursive function in a variable JavaScript

javascriptrecursionreturnreturn-value

提问by Wasea

I need to store the return value in a variable.

我需要将返回值存储在一个变量中。

I want to know how to fix this code. I know that if the value of b would be 3, I would get value=2, but if the function does more than one iteration I get unidentified. I read that I should use the callback or something but I don't know how, also an explanation of why my code doesn't work and how should I fix it. (Of course this code is for demonstration purpose as if I would show you the original it might get confusing.) Thanks a lot!

我想知道如何修复此代码。我知道如果 b 的值是 3,我会得到 value=2,但如果函数执行多次迭代,我会变得身份不明。我读到我应该使用回调或其他东西,但我不知道如何使用,还解释了为什么我的代码不起作用以及我应该如何修复它。(当然,此代码用于演示目的,好像我会向您展示原始代码一样,它可能会让人感到困惑。)非常感谢!

var b = 70;

function myfunction() {
    b--;
    if (b < 3) {
        return b;
    } else {
        myfunction();
    }
}
value = myfunction();
console.log(value);

采纳答案by Nik

Your code: myFunction()will return void/undefinedon first call, it is not a recursive approach.

您的代码:myFunction()undefined在第一次调用时返回 void/ ,这不是递归方法。

Following example is a recursive approach. A recursive function usually receive an argument to be processed and return a final value that bubbles(returned) up to the first caller.

以下示例是递归方法。递归函数通常接收一个要处理的参数并返回一个最终值,该值冒泡(返回)到第一个调用者。

function myfunction(b){
  b--;
  if(b<3) return b;
  else return myFunction(b);
}

When you call a recursive function, you should prepare a test for an escape. Otherwise you might end up in an infinite loop.

当你调用一个递归函数时,你应该准备一个逃逸测试。否则你可能会陷入无限循环。

Example of an infinite recursive

无限递归的例子

function badFunction(){
return badFunction();
}
// DON'T call badFunction()

Recursive Example

递归示例

var b = 70;
var safety = 1000;

function myfunction(local_b) {
  if(safety<0) return;
  safety--;

  // main task
  local_b--;
  
  if (local_b < 3) {
    return local_b;
  }

  return myfunction(local_b);

}
var value = myfunction(b); // when b = 70, value = 2
console.log(value);
document.getElementById('value').innerHTML = value;
<span id="value">_</span>

回答by SF_bs

var b = 70;

function myfunction() {
    b--;
    if (b < 3) {
        return b;
    } else {
        myfunction();
        return b;
    }
}
value = myfunction();
console.log(value);