js for loop output i is the same value problem

高洛峰
Release: 2017-03-01 16:11:36
Original
2038 people have browsed it

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

Copy after login


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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!