What triggered this question was the running result of a js program:
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 running result of this program is Result = 21;
From this program we can see that the value of i is 20 when function a returns, which is no problem.
When the b function returns, whether the value of i is 20 or 21 is worthy of discussion.
The essence of the problem is: should i be judged first, i<3, or i first, and then judge whether i<3.
According to the execution results, it can be seen that i was executed first.
function a(){
for(i= 0;i<20;i ){
// There is no var i
//The i here is a 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
a();// The return value of this function is i=20
//When i=20 passes through i and then i=21, then the condition of i<3 is not met and exits directly. So return i=21 which is normal!
}
return i;
}
var Result = b();
Here we complete the execution sequence of the for loop:
With the following program For example,
for(int i=0;i<10 ;i )
{
}
First execute i=0;i<10; and then execute the first round of the loop
and then execute: i ,i<10; then Execute the second round of loop body
until i >= 10 after the last i, at which point the loop ends.
That is,
statement 1 is executed before the loop (code block) starts.
statement 2 defines the conditions for running the loop (code block).
statement 3 is in Executed after the loop (block of code) has been executed