Javascript study notes array traversal and length properties

  • 2020-03-30 04:24:09
  • OfStack

Although arrays are objects in Javascript, it is not recommended to use a for in loop to iterate over groups, in fact, there are many reasons to prevent us from using a for in loop on arrays.
Because the for in loop will enumerate all the properties on the prototype chain, and the only way to stop it is to use hasOwnProperty, this will be much slower than a normal for loop.

traverse

The best way to traverse an array for optimal performance is to use the classic for loop.


var list = [1, 2, 3, 4, 5, ...... 100000000];
for(var i = 0, l = list.length; i < l; i++) {
    console.log(list[i]);
}

An extra trick here is to cache the length of the array by l = list.length.
Although the length property is defined in the array itself, there is still an overhead for each iteration of the loop. While the latest Javascript engines may have made performance improvements for this situation, there is no guarantee that your Javascript code will always run on this browser.
In fact, loops without cache length are much slower in performance than loops with cache length.

Length attribute

While the length property simply returns the number of elements in the array through getter methods, you can truncate the array through setter methods.


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 a larger number will not truncate the array.

conclusion

For optimal performance, it is recommended to use a for loop instead of a for in loop, and to cache the length attribute.

There are also array objects that have no methods, only a unique property called length. String objects have length methods ~~


Related articles: