Table of Contents
Classic For Loop
For... in And For… of
.forEach loop
结论
Home Web Front-end JS Tutorial Understand the 3 for loop styles in javascript and when to use them

Understand the 3 for loop styles in javascript and when to use them

Nov 26, 2020 pm 05:39 PM
for loop javascript

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
}
Copy after login

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/imghw/default1.png" data-src="https://img.php.cn/upload/image/758/933/751/1606383516520600.png" 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(
[在循环开始时只执行一次的表达式];
[其中每一个逻辑判断都需吻合的表达式];
[循环每一步都被执行的表达式]
)
Copy after login

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/imghw/default1.png" data-src="https://img.php.cn/upload/image/347/470/968/1606383547622810.png" 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/imghw/default1.png" data-src="https://img.php.cn/upload/image/347/470/968/1606383547622810.png" 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/imghw/default1.png" data-src="https://img.php.cn/upload/image/347/470/968/1606383547622810.png" 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]);
}
Copy after login

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)
}
Copy after login

Understand the 3 for loop styles in javascript and when to use them

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)
}
Copy after login

Understand the 3 for loop styles in javascript and when to use them

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)
}
Copy after login

Understand the 3 for loop styles in javascript and when to use them

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("-------")
    }
})()
Copy after login

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)
})
Copy after login

Understand the 3 for loop styles in javascript and when to use them

更快更简单,不是吗?

但是你可以看到我们如何在函数中很容易地使用所有属性。下面是一个您希望在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)
Copy after login

通过重写被调用函数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("-------")
})
Copy after login

结论

这就是我想要分享的关于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!

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)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks 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)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

How to use insertBefore in javascript How to use insertBefore in javascript Nov 24, 2023 am 11:56 AM

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

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

JavaScript and WebSocket: Building an efficient real-time image processing system JavaScript and WebSocket: Building an efficient real-time image processing system Dec 17, 2023 am 08:41 AM

JavaScript is a programming language widely used in web development, while WebSocket is a network protocol used for real-time communication. Combining the powerful functions of the two, we can create an efficient real-time image processing system. This article will introduce how to implement this system using JavaScript and WebSocket, and provide specific code examples. First, we need to clarify the requirements and goals of the real-time image processing system. Suppose we have a camera device that can collect real-time image data

See all articles