Understand the 3 for loop styles in javascript and when to use them
When learning any development language, the for loop is an essential syntax, and probably all developers will use it. It's so classic that every development language includes at least one version of the syntax for loops. However, JavaScript contains three different loop syntaxes (if you pay more attention, it can be counted as four).
The way they are used is not exactly the same, for example:
l Classic For loop syntax
l For….of and For…in
l A more showy version: .forEach
Next, I would like to introduce the similarities and differences when using these three syntaxes, and when and how to use them to achieve the best results. Okay, let's get started.
Classic For Loop
We should all be very clear about this syntax. In the for loop, you can define internal counters, set corresponding interrupt conditions and flexible stepping strategies ( Usually it can be either increasing or decreasing).
The syntax is:
for([计数器定义];[中断条件];[步进策略]){ //... TODO }
I’m sure even without my introduction, you must have written similar statements before, for example:
for(let counter = 0; counter <p>Let’s run it in Chrome After a while, the results obtained are also in line with expectations, but is that just the for loop? <br></p><p><img src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/image/758/933/751/1606383516520600.png?x-oss-process=image/resize,p_40" class="lazy" title="1606383516520600.png" alt="Understand the 3 for loop styles in javascript and when to use them"></p><p> You can think of the for loop as three expressions </p><pre class="brush:php;toolbar:false">for( [在循环开始时只执行一次的表达式]; [其中每一个逻辑判断都需吻合的表达式]; [循环每一步都被执行的表达式] )
The meaning of this expression is that you can use multiple counters to execute the for loop , or execute the code that needs to be executed each time in a step expression without affecting the counter, for example:
for(let a = 0, b = 0; a <p><img src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/image/347/470/968/1606383547622810.png?x-oss-process=image/resize,p_40" class="lazy" title="160638352246070Understand the 3 for loop styles in javascript and when to use them" alt="Understand the 3 for loop styles in javascript and when to use them"></p><p>We can go one step further and let it It becomes more in line with actual application scenarios: </p><pre class="brush:php;toolbar:false">for(let a = 0, b = 0; a <p><img src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/image/347/470/968/1606383547622810.png?x-oss-process=image/resize,p_40" class="lazy" title="160638352761244Understand the 3 for loop styles in javascript and when to use them" alt="Understand the 3 for loop styles in javascript and when to use them"></p><p>In addition, you can even replace the intermediate expression with a function call, as long as you remember that the return value of the function needs to be A Boolean type or a value that can be converted into a Boolean value is enough, for example: </p><pre class="brush:php;toolbar:false">function isItDone(a) { console.log("函数被调用!") return a <p><img src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/image/347/470/968/1606383547622810.png?x-oss-process=image/resize,p_40" class="lazy" title="160638353227285Understand the 3 for loop styles in javascript and when to use them" alt="Understand the 3 for loop styles in javascript and when to use them"></p><p>So, how to deal with asynchronous code in a classic for loop? How to ensure not to fall into the asynchronous trap? </p><p>I would like to introduce a new friend to you: async/await, which will make it easier and more controllable when we deal with asynchronous code, such as: </p><pre class="brush:php;toolbar:false">const fs = require("fs") async function read(fname) { return new Promise( (resolve, reject) => { fs.readFile(fname, (err, content) => { if(err) return reject(err) resolve(content.toString()) }) }) } (async () => { let files = ['file1.json', 'file2.json'] for(let i = 0; i <h2 id="For-in-And-For-of">For... in And For… of</h2><p> They look very similar, but they are not the same type of loop. </p><p>Let’s try to explain them as briefly as possible: </p><p>For…in loops through the enumerable properties of an object, that is when your custom object is used as a hash table or dictionary , it will be very simple to traverse them using For...in. </p><p>But please note that the traversal order is executed in element order, so please do not rely on the loop order. </p><pre class="brush:php;toolbar:false">let myMap { uno: 1, dos: 2, tres: 3 } for(let key in myMap) { console.log(key, "=", myMap[key]); }
It seems very simple, but please remember that For...in can only traverse an entity object. If you facilitate a non-entity, such as traversing a string, the following will happen:
for(let k in "Hello World!") { console.log(k) }
As you can see from the results, not every letter is traversed, but every attribute is traversed. As you can see, the numbers traversed are not useless. , because "Hello World!"[1] can also return the corresponding letters.
In contrast, if you want to iterate through each character, you need to use other variations: For…of
for(let char of "Hello World!") { console.log(char) }
This way of looping looks good for string Types are more efficient, and the same use case, because using this syntax, can return the corresponding value in the element. So we know from the above use cases that the content traversed by For...of is the value of the object.
We can see from the above example that they have one traversal attribute and one traversal value. So is there any way to obtain both the attribute and the value? The answer is yes. Using the entries method, you can obtain both at the same time. Properties and values, like this:
let myArr = ["hello", "world"] for([idx, value] of myArr.entries()) { console.log(idx, '=', value) }
Finally, what does it look like when dealing with asynchronous code? The answer is of course the same as the for loop.
const fs = require("fs") async function read(fname) { return new Promise( (resolve, reject) => { fs.readFile(fname, (err, content) => { if(err) return reject(err) resolve(content.toString()) }) }) } (async () => { let files = ['file2.json', 'file2.json'] for(fname of files) { let fcontent = await read(fname) console.log(fcontent) console.log("-------") } for(idx in files) { let fcontent = await read(files[idx]) console.log(fcontent) console.log("-------") } })()
Finally, we will use a short way to summarize the difference between For…in and For…of
For…in——Traversing attributes
For… of - Iterate over values
.forEach loop
This is probably my favorite one simply because I am a big fan of declarative syntax or the declarative way of writing code through imperatives.
Also, although the loop syntax above is also very useful and has good use cases, forEach is very useful when we need to focus on the data itself.
不管怎样,先撇开哲学上的争论不谈,.foreach方法是for循环的另一个版本,但是这个方法是数组对象的一部分,它的目的是接收一个函数和一个额外的可选参数,以便在执行函数时重新定义该函数的上下文。
对于数组中的每个元素,我们的函数都将被执行,并且它将收到三个参数(是的,就是三个,而不是一个,因为您已经习惯了使用它)。它们分别是:
正在处理的当前元素。
元素的索引,这已经简化了我们试图用for…of循环实现的任务
正在处理的实际数组。以防万一你需要做点什么。
那么,让我们看一个简单的示例:
a = ["hello", "world"] a.forEach ( (elem, idx, arr) => { console.log(elem, "at: ", idx, "inside: ", arr) })
更快更简单,不是吗?
但是你可以看到我们如何在函数中很容易地使用所有属性。下面是一个您希望在foreach方法上使用第二个可选参数的示例:
class Person { constructor(name) { this.name = name } } function greet(person) { console.log(this.greeting.replace("$", person.name)) } let english = { greeting: "Hello there, $" } let spanish = { greeting: "Hola $, ¿cómo estás?" } let people = [new Person("Fernando"), new Person("Federico"), new Person("Felipe")] people.forEach( greet, english) people.forEach( greet, spanish)
通过重写被调用函数greet的上下文,我可以在不影响其代码的情况下更改其行为。
最后,显示此方法也可以与异步代码一起使用,下面是示例:
const fs = require("fs") async function read(fname) { return new Promise( (resolve, reject) => { fs.readFile(fname, (err, content) => { if(err) return reject(err) resolve(content.toString()) }) }) } let files = ['file1.json', 'file2.json'] files.forEach( async fname => { let fcontent = await read(fname) console.log(fcontent) console.log("-------") })
结论
这就是我想要分享的关于JavaScript中关于循环的全部内容,我希望现在您对它们有了更清晰的理解,并且可以根据这些知识和我们当前的实际需求来选择您喜欢的循环。
原文地址:https://blog.bitsrc.io/3-flavors-of-the-for-loop-in-javascript-and-when-to-use-them-f0fb5501bdf3
更多编程相关知识,请访问:编程学习网站!!
The above is the detailed content of Understand the 3 for loop styles in javascript and when to use them. For more information, please follow other related articles on the PHP Chinese website!

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 English version
Recommended: Win version, supports code prompts!

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Dreamweaver CS6
Visual web development tools

Atom editor mac version download
The most popular open source editor
