The for loop is generally used to traverse arrays in javascript, as shown below:
Copy codeThe Code is as follows:
Var arr = [];
For (var I = 0; I <arr. length; I ++ ){
// Loop
}
The biggest problem with this kind of code is that the. length is obtained through the. Operator in each loop, increasing the overhead. So we can improve it in this way.
Copy codeThe Code is as follows:
Var arr = [];
For (var I = 0, n = arr. length; I <n; I ++ ){
// Loop
}
In this way, the arr. length is saved to the n variable first. It is obtained only once at the beginning.
But is that okay? It seems that n is a meaningless variable. Okay. continue to improve.
Copy codeThe Code is as follows:
Var arr = [];
For (var I = arr. length-1; I>-1; I --){
// Loop
}
In this case, we reverse the loop order and remove the n and use a constant-1.
If the for loop is not allowed in the Application Scenario. We can use while instead
Be good at using these two loop statements to improve javascript efficiency.
Copy codeThe Code is as follows:
Var arr = [];
Var I = arr. length-1;
While (I --){
// Loop arr [I]
}
Or
Copy codeThe Code is as follows:
Var arr = [];
Var I = arr. length-1;
Do {
// Loop arr [I]
} While (-- I)
In this way, the code is more concise and more efficient, especially if you can execute a loop body first, the use of do while is very effective.
The only problem is that I is moved out of the loop.