为什么没有&= t + + =在递归中工作?

时间:2017-01-20 12:26:22

标签: javascript recursion

我注意到如果我在递归中使用+=它会无限期地运行,因为终止语句中使用的变量的值不会增加。我无法弄清楚为什么,我已经在论坛上寻找答案,但没有看到答案。我试图弄清楚我是否做错了什么,如果不是,我正在寻找有关它为什么不起作用的具体细节的答案。

//this works fine
function recure(n = 0) {
    if (n > 10) {
        console.log('The End');
        return '';
    }
    console.log(n);
    setTimeout(function () {
        recure(n + 1)
    }, 1000);
}
recure();

//this also works fine, note it's working with n+=1
function loop(amount = 10, n = 1) {
    for (let i = 0; i < amount; i++) {
        console.log(n);
        n += 1;
    }
}

//This doesn't work and is the reason for the post, why?
function recure(n = 0) {
    if (n > 10) {
        console.log('The End');
        return '';  
    }
    console.log(n);
    n += 1;
    setTimeout(function () {
        recure()
    }, 1000);
}
recure();    //it indefinitely logs 0

4 个答案:

答案 0 :(得分:3)

n是函数特定调用的本地。由于您在没有参数的情况下调用函数,因此将绑定 new n绑定到0

function test(n=0){
  return n;
}

test();  //==> 0
test(2); //==> 2

递归并不是特别对待,所以如果你认为在调用n之间保持recure,这也应该发生:

function other(n=0) {
  return n;
}
function test(n=0) {
  n++;
  return other();
}

test(0); // ==> 1

然而,这是荒谬的,因为n是本地的,因此即使功能相同,每次通话都会赢得n

另请注意,第三个示例不是递归,因为调用堆栈被重置。

您致电recure的匿名函数在其词法范围内有n,因此您可以使用n+1调用它,以便新的recure获得一个n比一个来自thunk的调用高一个Link: https://jsbin.com/yibutifodo/1/edit?html,js,output

答案 1 :(得分:1)

在JavaScript中,变量范围由函数定义。因此,当您调用函数recure()时,将使用new&#34; N&#34;创建新范围。在每个范围内。

让我们试着了解你在这里做了什么:

1. You called recure(). 
 // No argument hence "N" is undefined therefore N is assigned 0.

2. You incremented value of "N"
 // New value of "N" = 1

3. You recursively called recure()
 // Again no argument hence "N" is 0
 // Since, recure() is called again new scope is created
 // This "N" is different from the "N" used is step 1

4. Bad recursion --> #Fail.

答案 2 :(得分:1)

&#13;
&#13;
//this works fine
function recure(n = 0){
    if (n > 10) {
        console.log('The End');
        return '';
    }
    console.log(n);
    setTimeout(function() {
        recure(n + 1)
    }, 1000);
}
recure();

//this also works fine, note it's working with n+=1
function loop(amount = 10, n = 1) {
    for (let i = 0; i < amount; i++) {
        console.log(n);
        n += 1;
    }
}

//This doesn't work and is the reason for the post, why?
function recure(n = 0) {
    if (n > 10) {
        console.log('The End');
        return '';  
    }
    console.log(n);
    n += 1;
  setTimeout(function(){recure(n)},1000);
}
recure();    //it indefinitely logs 0
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;
&#13;
&#13;

答案 3 :(得分:1)

这应该有效

function recure(n=0){
    if(n>10){
        console.log("The End");
        return "";  
      }
    console.log(n);
    n+=1;
    setTimeout(function(){recure(n)},1000);
  }
recure();

在递归的每个阶段,该特定闭包应该知道先前的递归状态。 我们通过'n'来了解递归的状态。

相关问题