What is the difference between “for in”, “for of” and “forEach”?

ForEach, forEach, forEach, forEach, forEach, forEach, forEach, forEach, forEach, forEach, forEach, forEach

First let’s look at for… in… The role of:

1.1 Enumerable Objects

        const star={
            name:'Iron Man'.gender:'male'.age:35
        };

        for(const k in star){
            console.log(k);   //name gender age
            console.log(star[k]); // Iron Man Man 35
        }
        
Copy the code

When using the for… in… Loop object that can iterate over property names and property values using for… of… An error is reported when traversing an object.

        const star={
            name:'Iron Man'.gender:'male'.age:35
        };

        for (const k of star) {
            console.log(k);   // star is not iterable
        }
Copy the code

So the for… of… You can’t loop over objects, so can forEach iterate over objects?

        const star = {
            name: 'Iron Man'.gender: 'male'.age: 35
        };

        star.foreach(function (i) {
            console.log(i);    //star.foreach is not a function
        })
Copy the code

You can see that forEach cannot traverse an object

1.2 Enumerable arrays

        const arr = ['tom'.'jarry'.'jack']
        
        for (const k in arr) {
            console.log(k);    / / 0 1 2
            console.log(arr[k]);   // tom jarry jack
        }
Copy the code

Output: 0 ‘Tom’ 1 ‘Jarry’ 2 ‘Jack’

It turns out that… The in… Is the output index value, through the index value can get the array data

Then use the for… of… The result is different

        const arr = ['tom'.'jarry'.'jack']

        for (const k of arr) {
            console.log(k);    / / 0 1 2
            console.log(arr[k]);   // undefined undefined undefined
        }
Copy the code

The output is 0 undefined 1 undefined 2 undefined

It turns out that… Of… Is the output array value

1.3 Enumerable prototype objects

        Array.prototype.sayHello = function () {
            console.log("Hello");
        }
        Array.prototype.str = 'world'
        var myArray = [1.2.3]
        myArray.name = 'array'

        for (let k in myArray) {
            console.log(k);    //0 1 2 name sayHello str
        }
Copy the code

The result shows that for in not only returns the index of the array, but also returns both the prototype object and the property value of the array object. One problem, however, is that these objects may not be needed in real development, and listing them all may create new problems.

So to solve this problem with prototype objects, you can use hasOwnProperty

        Array.prototype.sayHello = function () {
            console.log("Hello");
        }
        Array.prototype.str = 'world'
        var myArray = [1.2.3]
        myArray.name = 'array'

        for (let k in myArray) {
            if (myArray.hasOwnProperty(k)) {
                console.log(k);    //0 1 2 name}}Copy the code

Although hasOwnProperty is used, the properties of the array itself are still printed

The forEach role

1.1 Traversable number group

The problem with the above prototype object can be handled using forEach

        Array.prototype.sayHello = function () {
            console.log("Hello");
        }
        Array.prototype.str = 'world'
        var myArray = ['a'.'b'.'c']
        myArray.name = 'array'

        myArray.forEach((value, i) = > {
            console.log(value);
            console.log(i);
            // output 'a' 0 'b' 1 'c' 2
        })
Copy the code

With forEach, you can print index values and array values, and you won’t print an array prototype object

1.2 Failure to break

The problem with forEach is that it can’t break execution

        var arr = [1.2.3];

        arr.forEach(function (value) {
            console.log(value);
            if (value === 2) {
                return false}})/ / output 1, 2, 3
Copy the code

As you can see from the result, the return false is not executed, and it will run until the end

For in also has this problem:

        var arr = [1.2.3];

        for (let value in arr) {
            console.log(arr[value]);
            if (value == 5) {
                break; }}/ / output 1, 2, 3
Copy the code

As you can see from the result, break is not executed and will run until the end

1.3 the for… of… The role of

A traversable set of prototype objects can be processed using forEach as well as for of

        Array.prototype.sayHello = function () {
            console.log("Hello");
        }
        Array.prototype.str = 'world'
        var myArray = ['a'.'b'.'c']
        myArray.name = 'array'

        for (let index of myArray) {
            console.log(index);  // output a, b, and c
        }
Copy the code

Using for of does not print an index value, but it also does not print a prototype object for an array

For of resolves the problem of not being able to exit using break

        var arr = [1.2.3];
        for (let value of arr) {
            console.log(value);
            if (value == 2) {
                break}}/ / output 1, 2
Copy the code

As you can see, break breaks the loop

1.4 Iterable String

        let str = 'hello';

        for (let value of str) {
            console.log(value);   // 'h' 'e' 'l' 'l' 'o'
        }
Copy the code

1.5 Iterable Arguments class array object

        (function () {
            for (let k of arguments) {
                console.log(k);
            }
        })(1.2.3)
Copy the code

1.6 Iterable Map and set

        let mapData = new Map([['a'.1], ['b'.2], ['c'.3]])

        for (let [key, value] of mapData) {
            console.log(value);   / / 1, 2, 3
        }
Copy the code
        let setData = new Set([['a'.1], ['b'.2], ['c'.3]])

        for (let [key, value] of setData) {
            console.log(value);   / / 1, 2, 3
        }
Copy the code

The output is 1, 2, 3

Conclusion:

For in works for traversal of pure objects and outputs only enumerable properties

ForEach is useful for traversal of an array that needs to know the index value, but cannot be broken

For of is useful for array traversal without knowing the index value because it can be broken. In addition, for of is also more suitable for iterating over other strings, arrays of classes, and arrays of types