Home Web Front-end JS Tutorial Things to note when using for loops in javascript

Things to note when using for loops in javascript

Aug 22, 2017 am 11:11 AM
javascript js Precautions


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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Recommended: Excellent JS open source face detection and recognition project Recommended: Excellent JS open source face detection and recognition project Apr 03, 2024 am 11:55 AM

Face detection and recognition technology is already a relatively mature and widely used technology. Currently, the most widely used Internet application language is JS. Implementing face detection and recognition on the Web front-end has advantages and disadvantages compared to back-end face recognition. Advantages include reducing network interaction and real-time recognition, which greatly shortens user waiting time and improves user experience; disadvantages include: being limited by model size, the accuracy is also limited. How to use js to implement face detection on the web? In order to implement face recognition on the Web, you need to be familiar with related programming languages ​​and technologies, such as JavaScript, HTML, CSS, WebRTC, etc. At the same time, you also need to master relevant computer vision and artificial intelligence technologies. It is worth noting that due to the design of the Web side

Introduction to matters needing attention during the Mingchao test Introduction to matters needing attention during the Mingchao test Mar 13, 2024 pm 08:13 PM

During the Mingchao test, please avoid system upgrades, factory resets, and parts replacement to prevent information loss and abnormal game login. Special reminder: There is no appeal channel during the testing period, so please handle it with caution. Introduction to matters needing attention during the Mingchao test: Do not upgrade the system, restore factory settings, replace equipment components, etc. Notes: 1. Please upgrade the system carefully during the test period to avoid information loss. 2. If the system is updated, it may cause the problem of being unable to log in to the game. 3. At this stage, the appeal channel has not yet been opened. Players are advised to choose whether to upgrade at their own discretion. 4. At the same time, one game account can only be used with one Android device and one PC. 5. It is recommended that you wait until the test is completed before upgrading the mobile phone system or restoring factory settings or replacing the device.

How to start a live broadcast on Douyin for the first time? What should you pay attention to when broadcasting live for the first time? How to start a live broadcast on Douyin for the first time? What should you pay attention to when broadcasting live for the first time? Mar 22, 2024 pm 04:10 PM

With the rise of short video platforms, Douyin has become an indispensable part of many people's daily lives. Live broadcasting on Douyin and interacting with fans are the dreams of many users. So, how do you start a live broadcast on Douyin for the first time? 1. How to start a live broadcast on Douyin for the first time? 1. Preparation To start live broadcast, you first need to ensure that your Douyin account has completed real-name authentication. You can find the real-name authentication tutorial in &quot;Me&quot; -&gt; &quot;Settings&quot; -&gt; &quot;Account and Security&quot; in the Douyin APP. After completing the real-name authentication, you can meet the live broadcast conditions and start live broadcast on the Douyin platform. 2. Apply for live broadcast permission. After meeting the live broadcast conditions, you need to apply for live broadcast permission. Open Douyin APP, click &quot;Me&quot;-&gt;&quot;Creator Center&quot;-&gt;&quot;Direct

Steps and precautions for using localstorage to store data Steps and precautions for using localstorage to store data Jan 11, 2024 pm 04:51 PM

Steps and precautions for using localStorage to store data This article mainly introduces how to use localStorage to store data and provides relevant code examples. LocalStorage is a way of storing data in the browser that keeps the data local to the user's computer without going through a server. The following are the steps and things to pay attention to when using localStorage to store data. Step 1: Check whether the browser supports LocalStorage

Steps and precautions for installing pip without network Steps and precautions for installing pip without network Jan 18, 2024 am 10:02 AM

Methods and precautions for installing pip in an offline environment. Installing pip becomes a challenge in an offline environment where the network is not smooth. In this article, we will introduce several methods of installing pip in an offline environment and provide specific code examples. Method 1: Use the offline installation package. In an environment that can connect to the Internet, use the following command to download the pip installation package from the official source: pipdownloadpip This command will automatically download pip and its dependent packages from the official source and save it in the current directory. Move the downloaded compressed package to a remote location

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

The relationship between js and vue The relationship between js and vue Mar 11, 2024 pm 05:21 PM

The relationship between js and vue: 1. JS as the cornerstone of Web development; 2. The rise of Vue.js as a front-end framework; 3. The complementary relationship between JS and Vue; 4. The practical application of JS and Vue.

Frequently Asked Questions and Notes: Using MyBatis for Batch Query Frequently Asked Questions and Notes: Using MyBatis for Batch Query Feb 19, 2024 pm 12:30 PM

Notes and FAQs on MyBatis batch query statements Introduction MyBatis is an excellent persistence layer framework that supports flexible and efficient database operations. Among them, batch query is a common requirement. By querying multiple pieces of data at one time, the overhead of database connection and SQL execution can be reduced, and the performance of the system can be improved. This article will introduce some precautions and common problems with MyBatis batch query statements, and provide specific code examples. Hope this can provide some help to developers. Things to note when using M

See all articles