Usage of forEach, for in, for of loop in js

First, the general method of traversing an array:

    var array = [1,2,3,4,5,6,7];  
    for (var i = 0; i < array.length; i) {  
        console.log(i,array[i]);  
    }  

Second, use the for in square to traverse the array

    for(let index in array) {  
        console.log(index,array[index]);  
    };  

3. forEach

array.forEach(v=>{  
    console.log(v);  
});
array.forEach(function(v){  
    console.log(v);  
});
 

Fourth, using for in can not only operate on arrays, but also on enumerable objects

var A = {a:1,b:2,c:3,d:"hello world"};  
for(let k in A) {  
    console.log(k,A[k]);  
}

5. In ES6, a for of loop has been added, which is very simple to use

    for(let v of array) {  
        console.log(v);  
    };  

      let s = "helloabc"; 

      for(let c of s) {  

      console.log(c); 

     }

 

 To sum up: for in always gets the key or array of the object, the subscript of the string, and for of, like forEach, directly gets the value
result. for of cannot be used for objects.
For the new Map, Set above

    var set = new Set();  
    set.add("a").add("b").add("d").add("c");  
    var map = new Map();  
    map.set("a",1).set("b",2).set(999,3);  
    for (let v of set) {  
        console.log(v);  
    }  
    console.log("--------------------");  
    for(let [k,v] of map) {  
        console.log(k,v);  
    }  

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324548202&siteId=291194637