What caused this problem is the result of the running of a JS program:
The code copy is as follows:
var i = 0;
function a(){
for(i=0;i<20;i++){
}
}
function b(){
for(i=0;i<3;i++){
a();
}
return i;
}
var Result = b();
The result of this program running is Result = 21;
From this program we can see that there is no problem that the value of i is 20 when the function a returns.
When b function returns, it is worth discussing whether the value of i is 20 or 21.
The essence of the problem is: first determine whether i<3 or i++ is performed first, and then determine whether i<3.
According to the execution results, it can be seen that i++ was executed first.
The code copy is as follows:
function a(){
for(i=0;i<20;i++){
// No var i
//The i here is the global variable that everyone can access
}
}
function b(){
for(i=0;i<3;i++){
//alert(i);// Similarly, i here is also a global variable, returning 0 and only once returns
a();//This function returns i=20
//When i=20 passes i++ and i=21, then it does not meet the conditions of i<3 and exit directly. So return i=21 This is normal!
}
return i;
}
var Result = b();
Here we complete the execution order of the for loop:
The following program is an example
The code copy is as follows:
for(int i=0;i<10;i++)
{
}
First perform i=0;i<10; and then perform the first round of loop body
Then execute: i++, i<10; then execute the second round of loop body
Until the last i++ after i >=10, the loop ends.
Right now
Statement 1 is executed before the loop (code block) begins
Statement 2 Defines the conditions for running a loop (code block)
Statement 3 Executes after the loop (code block) has been executed