Prefacevar is a way to declare variables in ES5. I have always heard that when declaring variables with var, there is a problem of loop variables leaking to global variables, but I always can't figure out the impact of this "global". In addition, it is not clear when the output result is an increasing/decreasing value and when the output is the same value. Problem reproductionfor (var i = 1; i <= 5; i++) { setTimeout(function timer() { console.log(i) }, i * 1000) } Expected result: 12345 Print result: 66666 SolutionClosures for (var i = 1; i <= 5; i++) { (function (j) { setTimeout(function timer() { console.log(j) }, j * 1000) })(i) } setTimeout third parameter for (var i = 1; i <= 5; i++) { setTimeout( function timer(j) { console.log(j) }, i * 1000, i ) } Use let to define i for (let i = 1; i <= 5; i++) { setTimeout(function timer() { console.log(i) }, i * 1000) } letRegarding let, remember: the current i is only valid in this loop, and i in each loop is actually a new variable. The JavaScript engine will remember the value of the previous loop internally, and when initializing the variable i of this loop, it will perform calculations based on the previous loop. In addition, the for loop has another special feature, that is, the part that sets the loop variable is a parent scope, and the loop body is a separate child scope. for (let i = 0; i < 3; i++) { let i = 'abc'; console.log(i); } //abc //abc //abc SummarizeThis is the end of this article about how to solve the problems encountered when using var for loop. For more information about var for loop problems, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope you will support 123WORDPRESS.COM in the future! You may also be interested in:
|
<<: Explore the truth behind the reload process in Nginx
>>: Detailed explanation of the code for querying data of a certain day, month, or year in MySQL
Table of contents Listener watch Format Set up th...
UCenter Home is an SNS website building system rel...
Preface When backing up the database, a full data...
FIFO communication (first in first out) FIFO name...
Table of contents 1. Basic overview of the proces...
1. Summary of location usage Location can locate ...
The value of the background property in CSS backg...
Table of contents 1. Deploy consul cluster 1. Pre...
Table of contents Preface style-loader css-loader...
Table of contents Preface Lua Script nignx.conf c...
Table of contents 1. Scope 2. Function return val...
Table of contents Common array methods concat() M...
How to check the status of Linux firewall 1. Basi...
This article example shares the specific code of ...
During the Olympic Games, IE 8 Beta 2 will be rele...