【发布时间】:2017-01-20 20:37:10
【问题描述】:
我注意到如果我在递归中使用+=,它会无限期地运行,因为在终止语句中使用的变量的值不会增加。我不知道为什么,我已经在论坛上寻找答案但没有看到答案。我试图弄清楚我是否做错了什么,如果没有,我正在寻找关于它为什么不起作用的具体答案。
//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
【问题讨论】:
-
每次调用都会初始化一个本地的
n,其值为0。将n传递给递归调用。recurse(n) -
recure(n=0).... -
你没有传递
n的更新值所以它默认为0? -
将 setTimeout 更改为
setTimeout(function(){recure(n)},1000);
标签: javascript recursion