Home  >  Article  >  Web Front-end  >  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

青灯夜游
青灯夜游forward
2020-11-26 17:39:553227browse

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="https://img.php.cn/upload/image/758/933/751/1606383516520600.png" 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="https://img.php.cn/upload/image/156/104/357/160638352246070Understand%20the%203%20for%20loop%20styles%20in%20javascript%20and%20when%20to%20use%20them" 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="https://img.php.cn/upload/image/534/927/536/160638352761244Understand%20the%203%20for%20loop%20styles%20in%20javascript%20and%20when%20to%20use%20them" 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="https://img.php.cn/upload/image/985/386/873/160638353227285Understand%20the%203%20for%20loop%20styles%20in%20javascript%20and%20when%20to%20use%20them" 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>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)
}

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

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

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

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

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)

通过重写被调用函数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!

Statement:
This article is reproduced at:cnblogs.com. If there is any infringement, please contact admin@php.cn delete