Home > Web Front-end > JS Tutorial > Issues you should pay attention to when using for loops in javascript - with a summary of the problems_javascript skills

Issues you should pay attention to when using for loops in javascript - with a summary of the problems_javascript skills

WBOY
Release: 2016-05-16 15:44:31
Original
987 people have browsed it

Using a loop is convenient if you want to run the same code over and over again, with different values ​​each time.

Many times we use for loops, and the for loop department often loops over an array. Many times we write it like this:

// 次佳的循环
for (var i = 0; i < myarray.length; i++) {
  // 使用myarray[i]做点什么
}
Copy after login

Although there is no big problem with such code, it will get the length of the array every time it loops, which will reduce your code, especially when myarray is not an array, but a HTMLCollectionWhen object.

Look at the code below:

for (var i = 0, max = myarray.length; i < max; i++) {
  // 使用myarray[i]做点什么
}
Copy after login

This code will only obtain the length of the array once, which improves the quality of the code;

With the single var form, you can pull the variable out of the loop, like this:

function looper() {
  var i = 0,
    max,
    myarray = [];
  // ...
  for (i = 0, max = myarray.length; i < max; i++) {
   // 使用myarray[i]做点什么
  }
}
Copy after login

Summary of problems when JavaScript uses for loop

The discussion of this issue originally came from internal company emails. I just recorded the discussion of this issue.

When locating the problem, some project teams found that when using “for(x in array)”, unexpected values ​​of x appeared in the IE browser.

Specifically, if the Array.prototype.indexOf method is customized (for example, due to a certain prototype pollution), it may be because the old version of IE browser does not support the array.indexOf method, and the developer I really want to use it, but such a browser may cause the following problems:

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

//will output

1
2
function(){…}
Copy after login

In other words, the indexOf method is output.

The solution is simple, either don't add this method, or use a loop like "for (i=0; i < array.length; i )" etc.

But what is the nature of the problem? Some people speculate that it may be because the usage of for(x in obj) is actually to traverse an object, and the implementation of array is actually the same as that of ordinary objects, except that key is Just a given value:

{0:"something", 1:"something else"}
Copy after login

It was also mentioned in a stackoverflow question and answer that there is a difference between using for...in and for(;;) when traversing an array. The former means to enumerate the properties of the object. There are two problems:

The order of enumeration is not guaranteed;

Inherited properties are also enumerated;

In terms of support for Array.prototype.forEach, it can be clearly seen from this table that IE8 and below cannot be accurately supported:

Here is also a detailed explanation of the compatibility of the forEach method. In fact, major JavaScript frameworks (such as jQuery, Underscore, Prototype, etc.) all have safe and general implementations of for-each functionality.

It is also mentioned in the for in chapter of JSLint that the for in statement allows looping through the attribute names of the object, but it will also traverse those attributes inherited through the prototype chain, which in many cases will cause unexpected errors. . There is a crude solution:

for (name in object)

 { if (object.hasOwnProperty(name))

 { .... } }
Copy after login

Some people also mentioned the problem when using for(var i=0;i similar to this loop, because JavaScript does not have code block level variables, so the access of i here Permissions are actually the methods in which they are located. Some books will advise programmers to put such variable declarations in one place, but intuitively speaking, it is not reasonable enough in most cases.

Using "let" introduced in JavaScript 1.7 solves this problem, making i a true block-level variable:

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

Finally, Google’s JavaScript style guide also involves this constraint:

for-in loop:


Only for iterating over keys in an object/map/hash
Copy after login

The above is the entire content of this article about the issues that should be paid attention to when using for loops in JavaScript - with a summary of the issues. I hope it will be helpful for future work and study. We welcome criticism and suggestions from industry insiders.

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template