Explore the order in which the three parts of the For loop are executed separated by semicolons
- 2020-03-30 03:06:52
- OfStack
What causes this question is the result of running a js program:
Result = 21;
And what we can see from this program is that I is going to be 20 when a returns and that's fine.
And when b returns, it's worth discussing whether I is 20 or 21.
The essence of the problem is that the judgment was made first. 3. Once again, i++ was conducted first, and then i< was judged; 3.
As you can see from the results of the execution, i++ was executed first.
Here we complete the execution order of the for loop:
Take the following program as an example
I =0; I< 10; Then execute the first round of the loop body
Then execute: i++,i< 10; Then execute a second round of the loop body
Until the last I ++ after I > =10, and the loop ends.
namely
Statement 1 is executed before the loop (block of code) begins
Statement 2 defines the conditions for running the loop (block of code)
Statement 3 is executed after the loop (block of code) has been executed
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();
Result = 21;
And what we can see from this program is that I is going to be 20 when a returns and that's fine.
And when b returns, it's worth discussing whether I is 20 or 21.
The essence of the problem is that the judgment was made first. 3. Once again, i++ was conducted first, and then i< was judged; 3.
As you can see from the results of the execution, i++ was executed first.
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);// Same thing here i Also a global variable, returns 0 And only return once
a();//This function returns I =20
//When I =20 goes through I ++, I =21, then it does not conform to i<Condition of 3, exit directly. So return I =21 which is normal!
}
return i;
}
var Result = b();
Here we complete the execution order of the for loop:
Take the following program as an example
for(int i=0;i<10;i++)
{
}
I =0; I< 10; Then execute the first round of the loop body
Then execute: i++,i< 10; Then execute a second round of the loop body
Until the last I ++ after I > =10, and the loop ends.
namely
Statement 1 is executed before the loop (block of code) begins
Statement 2 defines the conditions for running the loop (block of code)
Statement 3 is executed after the loop (block of code) has been executed