Generally in JavaScript, the array is traversed by using a for loop, as in the following
Copy Code code as follows:
var arr = [];
for (var i=0; i<arr.length; i++) {
Loop
}
The biggest problem with this code is that it gets. Length at every loop, adding to the overhead. So we can improve on that.
Copy Code code as follows:
var arr = [];
For (Var i=0, n=arr.length i<n; i++) {
Loop
}
In this way, first arr.length to the n variable. Gets only once at the start.
But is this going to be a problem? Seems to define a more meaningless variable N. Okay, then keep improving.
Copy Code code as follows:
var arr = [];
for (Var i=arr.length-1 i >-1; i--) {
Loop
}
Okay, so we're going to turn this loop upside down and we'll take that n out and use a constant-1.
If the scenario is applied, it is allowed to not use a for loop. We can use while instead
Good at using both loops to improve javascript efficiency.
Copy Code code as follows:
var arr = [];
var i=arr.length-1;
while (i--) {
Loop Arr[i]
}
Or
Copy Code code as follows:
var arr = [];
var i=arr.length-1;
do {
Loop Arr[i]
}while (I.)
This makes the code simpler and more efficient, especially if you allow the loop body to be executed first, using the do-while effect is obvious.
The only problem is to move I out of the loop.