Home > Web Front-end > JS Tutorial > body text

Things to note when using for loops in javascript

巴扎黑
Release: 2017-08-22 11:11:54
Original
1758 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 such code What a big problem, but each loop will get the length of the array, which will reduce your code this time, especially when myarray is not an array, but an HTMLCollection object.

Look at the following code again:

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 take the variables 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 using for loops in javascript

The discussion of this issue originally came from the company's internal email, I just put this issue record the discussion.

Some project teams discovered when locating problems that when using "for(x in array)"this way of writing, x appeared unexpectedly under the IE browser value.

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 developers want to use it, so such a browser may have such a problem:

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

//will output

1
2function(){…}
Copy after login

In other words, put indexOfThis method is output.

The solution is very 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 for(x in obj) is actually used to traverse an object, and the implementation of array is actually the same as an ordinary object, except that key is It’s just a given value:

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

It was also mentioned in a stackoverflow Q&A 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 cannot be guaranteed;

Inherited properties are also enumerated;

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

There is also compatibility with the forEach method. Elaborate. 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 the loop to traverse the property names of the object, but it will also traverse those properties inherited through the prototype chain, which in many cases will cause unexpected other than errors. There is a crude solution:

for (name in object)
 { if (object.hasOwnProperty(name))
 { .... } }
Copy after login

Some people also mentioned the problem of using for(var i=0;i similar to this loop, because JavaScript has no code Block-level variables, so the access permission of i here is actually the method where it is 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 can solve this problem, making i a real code block level variable:

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

Finally, in Google's JavaScript style guide, also This constraint is involved:

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 - a summary of the issues is attached. I hope it will be helpful for future work and study. We also welcome criticisms from industry insiders. suggestion.

The above is the detailed content of Things to note when using for loops in javascript. For more information, please follow other related articles on the PHP Chinese website!

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