search
HomeWeb Front-endJS TutorialThings to note when using for loops in javascript

Things to note when using for loops in javascript

Aug 22, 2017 am 11:11 AM
javascriptjsPrecautions


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]做点什么}

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]做点什么}

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]做点什么
 }}

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);

//will output

1
2function(){…}

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 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"}

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))
 { .... } }

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++)

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

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
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
From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

See all articles

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software