Home  >  Article  >  Web Front-end  >  Javascript study notes: Array traversal and length attribute_Basic knowledge

Javascript study notes: Array traversal and length attribute_Basic knowledge

WBOY
WBOYOriginal
2016-05-16 16:30:431423browse

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

Traverse

For best performance, the best way to iterate over an array is to use a classic for loop.

Copy code 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]);
}

An extra trick here is to cache the length of the array via l = list.length.
Even though the length property is defined on the array itself, there is still overhead on each iteration of the loop. Although the latest Javascript engine may have performance optimizations for this situation, there is no guarantee that your Javascript code will always run in this browser.
In fact, loops with uncached lengths are much slower than loops with cached lengths.

length attribute

Although the length property only returns the number of elements in the array through the getter method, the array can be truncated through the setter method.

Copy code 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, undefined, undefined, 4]

Assigning a smaller number to the length property will truncate the array, while assigning a larger number will not truncate the array.

Summary

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

There are also array objects that do not have any methods, only one unique attribute length. String objects have length methods~~

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