JS 3 styles For loop what similarities and differences?

Please indicate the source: Grape City's official website , Grape City to provide professional development tools for developers, solutions and services, enabling developers.
Original Source: https: //blog.bitsrc.io/3-flavors-of-the-for-loop-in-javascript-and-when-to-use-them-f0fb5501bdf3

 

In any development language learning time, for circulation is essential syntax, may all developers will use it. It is very classic, so that each include at least one programming language syntax version on cycle. However, JavaScript contains three different kinds of loop syntax (if we pay attention to it, may be counted as are the four).

Their use is not exactly the same, for example as follows:

l For the classic loop syntax

l  For….of 及 For…in

l virtuoso point version: .forEach

Next, I would like to introduce the next time what the similarities and differences of these three syntax to use, and how to use them to gain the best results at what time. Okay, let's get started.

For cycling classic

This syntax we should have been very clear, in a for loop, in which you can define the internal counter, set the corresponding interrupt conditions and flexible stepper strategy (usually can be incremented also be decremented).

The syntax is:

for ([Definition Counter]; [interrupt condition]; [step policy]) {
    // ... 
    the TODO 
}

 

I'm not even sure my presentation before you must also wrote a similar statement, for example:

for(let counter = 0; counter < 10; counter++) {
console.log(counter)
}

 

Let's run it in Chrome, the result is also in line with expectations, but for loop is just so yet?

 

You can think of for loop is three expressions

for ( 
[at the beginning of the cycle is performed only once expressions]; 
[wherein each logical judgment are required to match expressions]; 
[cycles per step are executed expression] 
)

 

Such expression meaning that you can use a plurality of counters for loop or execution code to be executed in each step expression without affecting the counter of, for example:

for(let a = 0, b = 0; a < 10 && b < 100; a++, b+=10) {
   console.log(a, b)
}

 

We can go further, let it become more realistic scenarios:

for (the let A = 0, B = 0; A <B && 10 <100; the console.log ( "you are now counters:", ++ a, b + = 2)) {}

 

In addition, you can even replace the middle expression is a function call, as long as you remember, the return value of the function needs to be a Boolean or can be converted to a boolean value. For example:

function isItDone(a) {
 console.log("函数被调用!")
 return a < 10
}

for(let a = 0; isItDone(a); a++) {
 console.log(a)
}

 

 

Then, in the classic cycle for how to handle asynchronous code? How to ensure it does not fall into the trap of asynchronous?

I introduce to you a new friend: async / await, this will make us easier when dealing with asynchronous code, controlled, such as:

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 < files.length; i++) {
        let fcontent = await read(files[i])
        console.log(fcontent)
        console.log("-------")
    }
})()

For... in 及 For… of

They look very similar, but they are not the same type of cycle.

Let us try to explain them briefly:

For ... in loop through the enumerable object's attributes, that is when your custom object is used as a hash table or dictionary, use the For ... in time they will become very simple traversal.

However, please note that the traversal order is based on the elements of order execution, so please do not rely on the order cycle.

let myMap {
  uno: 1,
  dos: 2,
  tres: 3
}
for(let key in myMap) {
  console.log(key, "=", myMap[key]);
}

 

Looks very simple, but remember, For ... in only traverse a physical object, if convenient a non-entity, such as traversing a string, then the situation will take place as follows:

for(let k in "Hello World!") {
   console.log(k)
}

 

You can see from the results, did not traverse out each letter, but to traverse each attribute, as you can see, traversing the figure is not no use, because "Hello World!" [1] is the same returns the corresponding letters.

Conversely, if you want to walk through each character, you need to use other variants: For ... of

for(let char of "Hello World!") {
  console.log(char)
}

 

This cycle approach seems more effective type of string, the same use case, because of the use of this syntax, it is possible to return to a value corresponding to the element. Therefore, we found that the above use cases, For ... of traversed the object is the value of the content.

Through the above examples we can see that they traverse each other a property, a traversal value, then there is no way we can get both property values ​​and get it, the answer is yes, use entries method, you can get properties and values ​​at the same time, as follows It shows:

let myArr = ["hello", "world"]
for([idx, value] of myArr.entries()) {
    console.log(idx, '=', value)
}

 

 

Finally, when dealing with asynchronous code, what is it? The answer of course is 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 again use the short way to summarize For ... in and For ... of difference

For ... in-- traverse the property

For ... of-- traversal value

.forEach cycle

This is probably my favorite one, simply because I like the declarative syntax or code written in a declarative way through imperative.

And when, in spite of the above loop syntax as well, and has a very good use cases, but we need to focus on the data itself, forEach good use.

In any case, first put aside the debate on the philosophy aside, .foreach method is another version of the for loop, but this method is part of an array of objects whose purpose is to receive a function and an additional optional parameters in order to perform redefine the function when the function context.

For each element in the array, our function will be executed, and it will receive three parameters (Yes, that's three, rather than one, because you're used to using it). they are, respectively:

  1. The current element being processed.
  2. Index of the element, which has simplified our task of trying to use for ... cycle implementation
  3. The actual array being processed. Just in case you need to do something.

So, let's look at a simple example:

a = ["hello", "world"]

a.forEach ( (elem, idx, arr) => {
   console.log(elem, "at: ", idx, "inside: ", arr)
})

 

Faster and easier, is not it?

But you can see how we can easily use all of the properties in the function. Here's an example you want to use the optional second parameter in the foreach method:

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)

 

By rewriting the context of the called function greet, I can change their behavior without affecting their code.

Finally, the display method may also be used with asynchronous code, the following are examples:

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

 

in conclusion

This is what I want to share about the JavaScript on the entire contents of the cycle, I hope you now have a clearer understanding of them, and can select your favorite cycle according to our current knowledge and actual needs.

Guess you like

Origin www.cnblogs.com/powertoolsteam/p/3type-forloop.html