Javascript 使用回调/闭包/参数在js中循环

Javascript 使用回调/闭包/参数在js中循环,javascript,callback,closures,Javascript,Callback,Closures,我从这篇文章中了解了js闭包: 我想体验一下,所以我试着创建一个循环,通过创建一个对函数本身使用回调的函数,我将增加一个参数并显示结果 起初它不起作用,后来我改变了我增加论点的方式,它起作用了: function test1(i1){ console.log("test1 : "+i1.toString()); setTimeout(function(){test1(i1++);},2500); } function test2(i2){ console.log("test2 :

我从这篇文章中了解了js闭包:

我想体验一下,所以我试着创建一个循环,通过创建一个对函数本身使用回调的函数,我将增加一个参数并显示结果

起初它不起作用,后来我改变了我增加论点的方式,它起作用了:

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
i2 = i2 + 1;
test2(i2);
而在另一个功能中

function test2(i2){
  console.log("test2 : "+i2.toString());
  setTimeout(function(){test2(++i2);},2500);
}
相当于

test1(i1); // it is always getting called with value = 0
i1++; // later being incremented but not used
i2 = i2 + 1;
test2(i2);

为什么不在将i1传递给test1之前增加它的值呢。函数启动后是否进行计算?它是否通过了计算而不是计算结果?如果是,为什么它“执行”++i2(之前?)将其传递给test2?i1++意味着,传递i1的当前值,然后在下一步中递增,++i2意味着先递增,然后传递给函数好的,我永远不会猜到^^。谢谢你!如果在
test1(i1++)
之后调试或添加另一个
console.log
,您会看到它确实会增加到
1
,只是在执行了上面讨论过的函数之后才这样做!这与闭包无关,更多的是与执行顺序有关。编辑得好:)