1. I recently encountered a problem during development, why is the output always 5, instead of clicking on each p, the corresponding 1, 2, 3, 4, 5 will be alerted.
The code is as follows:
闭包演示 1
2
3
4
5
At this time, click on any p and the pop-up will be 5
Reason:js event processor will not run during the idle time of the thread, resulting in the final run time What is output is the last value of i, that is: 5
2. Solution: Use closure to protect the value of variable i.
//sava1:加一层闭包,i以函数参数形式传递给内层函数 for( var i=0; i Copy after login
The above article briefly discusses the problem of js for loop outputting i as the same value, which is all the content shared by the editor. , I hope it can give everyone a reference, and I also hope everyone will support the PHP Chinese website.
For more articles related to the problem of js for loop outputting i as the same value, please pay attention to the PHP Chinese website!