Generally, when traversing an array in javascript, a for loop is usually used, like the following
var arr = [];
for(var i=0; i
//loop
}
this The biggest problem with this code is that each time it is looped, .length must be obtained through the .operator, which increases the overhead. Then we can improve like this.
var arr = [];
for(var i=0, n=arr.length; i//loop
}
In this way, first temporarily store arr.length into the n variable go. Get it only once at the beginning.
But is this okay? It seems that an extra meaningless variable n is defined. Okay, then continue to improve
var arr = [];
for(var i=arr.length-1; i > -1; i--){
//loop
}
Okay, let’s loop this Reverse the order, remove the n, and use a constant -1.
If the application scenario allows you not to use a for loop. We can use while instead of
to make good use of these two loop statements to improve the efficiency of javascript.
var arr = [];
var i= arr.length-1;
while(i--){
//loop arr[i]
}
or
var arr = [];
var i=arr.length-1;
do {
// loop arr[i]
}while(--i)
This way the code is simpler and more efficient, especially if the loop body is allowed to be executed once Next, the effect of using do while is obvious.
The only problem is moving i outside the loop.
Statement:The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn