Although arrays are objects in Javascript, it is not recommended to use a for in loop to traverse an array, in fact, there are many reasons to prevent us from using the for in loop for arrays.
Because the for in loop will enumerate all the attributes on the prototype chain, and the only blocking method is to use hasOwnProperty to determine, this will be much slower than the normal for loop.
Traverse
The best way to traverse an array for maximum performance is to use the classic for loop.
Copy Code code as follows:
var list = [1, 2, 3, 4, 5, ... 100000000];
for (var i = 0, L = list.length i < l; i++) {
Console.log (List[i]);
}
One of the extra tricks here is to cache the length of an array through L = list.length.
Although attribute length is defined in the array itself, there is still a cost for each traversal of the loop. Although the latest JavaScript engine may have done a performance tuning on this situation, you are not sure that your JavaScript code will always run on this browser.
In fact, a loop that does not cache length is slower than the cycle performance of the cache length.
Length Property
Although the length property simply returns the number of elements in an array through the Getter method, the array can be truncated by setter methods.
Copy Code code as follows:
var foo = [1, 2, 3, 4, 5, 6];
Foo.length = 3;
Foo [1, 2, 3]
Foo.length = 6;
Foo.push (4);
Foo [1, 2, 3, undefined, undefined, undefined, 4]
Assigning a smaller number to the length property will truncate the array, and the array will not be truncated if a larger number is assigned.
Summarize
For optimal performance, it is recommended that you use a for loop instead of using a for in loop, while caching the length property.
There are also array objects that have no method, only a single attribute length. The string object has a length method.