We usually use loops to traverse arrays, and loops are always a common source of JavaScript performance problems. Sometimes, poor loops can seriously reduce the code running speed. The attributes of an array can be divided into three types: length attribute, index attribute, and other attributes. Compared with common objects, the special attribute of an array object is its length attribute and index attribute. Although arrays are objects in Javascript, we do not recommend that you use the for in loop to traverse arrays. 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 attributes of the prototype chain, and the only way to block it is to use hasOwnProperty for judgment, this will be much slower than the normal for loop.
Traversal
In order to achieve the best performance to traverse an array, the best way is to use the classic for loop.
The Code 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]);
}
Here is an extra TRICK: cache the length of the array through l = list. length.
Although the attribute length is defined in the array itself, there is still an overhead in every loop. Although the latest Javascript Engine may have optimized the performance of this situation, you cannot guarantee that your Javascript code will always run on this browser.
In fact, a loop with no cache length is much slower than a loop with a cache length.
Length attribute
Although the length attribute only returns the number of elements in the array through the getter method, you can use the setter method to truncate the array.
The Code 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, 4]
If you assign a smaller value to the length attribute, the array is truncated. If you assign a larger value to the length attribute, the array is not truncated.
Summary
To achieve optimal performance, we recommend that you use a for loop instead of a for in loop and cache the length attribute.
There is also no method for array objects, and there is only one unique attribute length. The string object has the length method ~~