我正在从这篇文章中了解 js 闭包:How do JavaScript closures work? .
我想体验一下,所以我尝试通过创建一个在函数本身上使用回调的函数来创建一个循环,这样做会增加一个参数并显示结果。
起初它没有用,然后我改变了我增加参数的方式并且它起作用了:
function test1(i1){
console.log("test1 : "+i1.toString());
setTimeout(function(){test1(i1++);},2500);
}
function test2(i2){
console.log("test2 : "+i2.toString());
setTimeout(function(){test2(++i2);},2500);
}
test1(0);
test2(0);
只是将i++改为++i。
输出如下:
test1 : 0
test2 : 0
undefined
test1 : 0
test2 : 1
test1 : 0
test2 : 2
test1 : 0
test2 : 3
test1 : 0
test2 : 4
test1 : 0
test2 : 5
为什么第一步不行?
编辑 2:我知道 i++ 和++i 之间的区别,但它不应该工作吗?
编辑:肯定与闭包有关......
最佳答案
在
function test1(i1){
console.log("test1 : "+i1.toString());
setTimeout(function(){test1(i1++);},2500);
}
您总是使用与 i1 相同的值调用 test1(),然后递增它。
因为你总是用值 0 调用它,所以你得到 0 作为输出
test1(i1++)
相当于
test1(i1); // it is always getting called with value = 0
i1++; // later being incremented but not used
在其他函数中
function test2(i2){
console.log("test2 : "+i2.toString());
setTimeout(function(){test2(++i2);},2500);
}
相当于
i2 = i2 + 1;
test2(i2);
关于javascript - 使用回调/闭包/参数在 js 中循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46091779/