JavaScript Learning notes array traversal and length properties _ Basics

Source: Internet
Author: User
Tags truncated

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.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.