Notes for using the for Loop in javascript-appendix _ javascript tips-js tutorial

Source: Internet
Author: User
A for Loop is a tool that is often used to repeatedly execute code and create a for loop, this article mainly introduces the issues that you should pay attention to when using the for Loop in javascript-with a summary of the problem, you can refer to if you want to run the same code over and over again, and each time the values are different, it is very convenient to use the loop.

Most of the time we use the for loop, while the for loop Department often loops an array, which is often written as follows:

// The second best loop for (var I = 0; I <myarray. length; I ++) {// use myarray [I] To Do Something}

Although such code is not a big problem, every cycle will get the length of the array, this reduces your code, especially whenMyarrayIt is not an array, butHTMLCollectionObject.

Let's look at the following code:

For (var I = 0, max = myarray. length; I <max; I ++) {// What To Do With myarray [I}

In this way, the Code only gets the length of the array once, improving the quality of the Code;

With the single var form, you can extract variables from the loop, as shown below:

Function logoff () {var I = 0, max, myarray = []; //... for (I = 0, max = myarray. length; I <max; I ++) {// use myarray [I] To Do Something }}

Summary of problems when javascript uses the for Loop

The discussion of this issue was initially from an internal company email. I just recorded the discussion of this issue.

Some project teams found that they are using"For (x in array )"In this way, in the IE browser, x displays unexpected values.

SpecificallyArray. prototype. indexOfMethod (for example, due to prototype pollution), it may be because the old version of IE does not support the array. indexOf method, and developers are eager to use it, so such a browser may have this problem:

Array.prototype.indexOf = function(){...};var arr = [1, 2];for (x in arr) console.log(x);

// Output

12function(){…}

In other wordsIndexOfThis method is output.

The solution is very simple, either do not add this method, or use"For (I = 0; I <array. length; I ++ )"Such a loop.

But what is the nature of the problem? Someone guessed that it could be becauseFor (x in obj)This is actually used to traverse an object, and the implementation of array is actually consistent with that of common objects,KeyIt is an established value:

{0:"something", 1:"something else"}

As mentioned in a stackoverflow Q & A,... The difference between in and for (;) is that the former represents the attributes of enumeration objects, and there are two problems:

The order of enumeration cannot be guaranteed;

The inherited attributes are also enumerated;

InArray. prototype. forEachIn this table, we can also clearly see that IE8 and earlier versions cannot be accurately supported:

The compatibility of the forEach method is described in detail here. In fact, the main JavaScript frameworks (such as jQuery, Underscore, and Prototype) have safe and general for-each functions.

As mentioned in the for in section of JSLint, The for in statement allows loop traversal of the object's attribute names, but also traverses the attributes inherited by the prototype chain, this may cause unexpected errors in many cases. There is a crude solution:

for (name in object) { if (object.hasOwnProperty(name)) { .... } }

Some people mentioned the usageFor (var I = 0; I Similar to this loop, because JavaScript does not have code block-level variables, the I access permission here is actually the method. In some books, programmers are advised to place such variable declarations in one place, but in a straightforward sense, they are not reasonable in most cases.

Using the "let" introduced in JavaScript 1.7 can solve this problem and make I a real variable at the code block level:

for(let i =0; i < a.length; i++)

Finally, this constraint is also involved in Google's JavaScript style guidance:

for-in loop:Only for iterating over keys in an object/map/hash

The above are all the questions you should pay attention to when using the for Loop in javascript in this article-with a summary of the issues, I hope to help you in your future work and study, and I also welcome comments and suggestions from industry insiders.

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.