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 a for in loop for arrays.
Because the for in loop will enumerate all properties on the prototype chain, and the only way to prevent it is to use hasOwnProperty to judge, which will be much slower than the normal for loop.
Traversal
For optimal performance to traverse an array, the best way is to use the classic for loop.
The code copy is as follows:
var list = [1, 2, 3, 4, 5, ...... 100000000];
for(var i = 0, l = list.length; i < l; i++) {
console.log(list[i]);
}
There is an extra trick here, which is to cache the length of the array by l = list.length.
Although the property length is defined in the array itself, there is still overhead at each traversal of the loop. Although the latest Javascript engines may have performed performance optimizations for this situation, you cannot guarantee that your Javascript code will always run on this browser.
In fact, loops without cache lengths are much slower than loops with cache lengths.
length attribute
Although the length attribute only returns the number of elements in the array through the getter method, the array can be truncated by the setter method.
The code copy is 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 attribute will truncate the array, and if assigned a larger number, it will not truncate the array.
Summarize
For optimal performance, it is recommended to use a for loop instead of a for in loop while caching the length attribute.
There is also array objects that have no method, only a unique attribute length. String objects have length methods~~