For Each, for...in, for...of the loop method in JavaScript

Keywords: IE Javascript Attribute

JavaScript has been around for more than 20 years, and the way we've been using it to loop an array is this:

for (var index = 0; index < myArray.length; index++) {
console.log(myArray[index]);
}

I. forEvery

Since JavaScript 5, we have been able to use the built-in forEach method: the function callback in the forEach method has three parameters: the first parameter is the traversal array content, the second parameter is the corresponding array index, and the third parameter is the array itself. Examples are as follows:

var arr = [1,2,3,4];
arr.forEach(function(value,index,array){
    array[index] == value;    //The result is true
    sum+=value;  
    });
console.log(sum);    //The result is 8
myArray.forEach(function (value) {
console.log(value);
});

But above, the code can not work properly in IE. Because Array of IE does not have this method.

alert(Array.prototype.forEach);  

To execute the above sentence, you get "undefined". That is to say, Array has no method for Each in IE.

If you want to use this method in IE, you need to manually add the prototype method to it.

if (!Array.prototype.forEach) {  
    Array.prototype.forEach = function(callback, thisArg) {  
        var T, k;  
        if (this == null) {  
            throw new TypeError(" this is null or not defined");  
        }  
        var O = Object(this);  
        var len = O.length >>> 0; // Hack to convert O.length to a UInt32  
        if ({}.toString.call(callback) != "[object Function]") {  
            throw new TypeError(callback + " is not a function");  
        }  
        if (thisArg) {  
            T = thisArg;  
        }  
        k = 0;  
        while (k < len) {  
            var kValue;  
            if (k in O) {  
                kValue = O[k];  
                callback.call(T, kValue, k, O);  
            }  
            k++;  
        }  
    };  
}  

Compared with the traditional way of writing, forEach is much simpler, but it also has the disadvantage: you can't interrupt the loop (use statements or use statements). You can use the following two ways:

1. if statement control
2. return . (return true, false)

The following example is to take out the multiples of 2 and 3 in the array:

arryAll.forEach(function(e){  
    if(e%2==0)  
    {  
        arrySpecial.push(e);  
        return;  
    }  
    if(e%3==0)  
    {      
        arrySpecial.push(e);  
        return;  
    }  
}) 

Two, for... in

for-in loops are actually designed for looping "enumerable" objects.

var obj = {a:1, b:2, c:3};
for (var prop in obj) {
console.log("obj." + prop + " = " + obj[prop]);
}
// Output:
// "obj.a = 1"
// "obj.b = 2"
// "obj.c = 3"

You can also use it to loop an array:

for (var index in myArray) { // This is not recommended.
console.log(myArray[index]);
}

It is not recommended to use for-in to loop an array because, unlike objects, the index of an array is different from ordinary object attributes and is an important indicator of numerical sequence. Also note that the for in loop does not arrange the output according to the attribute subscripts.

"first":"first",
   "zoo":"zoo",
  "2":"2",
  "34":"34",
  "1":"1",
  "second":"second"
};
for (var i in obj) { console.log(i); };
//Output:
1
2
34
first
zoo
second

Execute according to chrome, first put out the non-negative integer key, sort the output, and then output the order of the remaining definitions. Because of this wonderful setting, avalon's ms-with objects are not sorted as expected. Users can only be forced not to define key names in pure numbers.

In short, for - in is a method for looping objects with string key s.

Three, for... of

JavaScript 6 introduces a new method of loop, for-of loop, which is simpler than the traditional for loop and makes up for the shortcomings of forEach and for-in loop. Let's first look at its for-of grammar:

for (var value of myArray) {
console.log(value);
}

The grammar of for-of looks very similar to for-in, but it has a lot of functions, it can recycle a lot of things.

for-of recycling example:

let iterable = [10, 20, 30];
for (let value of iterable) {
console.log(value);
}
// 10
// 20
// 30

We can use it instead, so that it becomes an unmodifiable static variable in a loop.

let iterable = [10, 20, 30];
for (const value of iterable) {
console.log(value);
}
// 10
// 20
// 30

Loop a generator:

function* fibonacci() { // a generator function
let [prev, curr] = [0, 1];
while (true) {
[prev, curr] = [curr, prev + curr];
yield curr;
}
}
for (let n of fibonacci()) {
console.log(n);
// truncate the sequence at 1000
if (n >= 1000) {
break;
}

Fourthly, an example shows that for uuuuuuuuuuuu in, for... of difference

for in is the traversal key name and for of is the traversal key value. For example:

let arr = ["a","b"];
for (a in arr) {
    console.log(a);//0,1
}

for (a of arr) {
    console.log(a);//a,b
}

Because of this feature of for of, he can also traverse iterator objects, and for in is a simple traversal.

Posted by PJSheltrum on Tue, 01 Jan 2019 01:24:08 -0800