The usage of forEach, for in, for of loop in js

Posted by jandrews3 on Tue, 03 Mar 2020 12:01:29 +0100

1, General method of traversing array:

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

2, Traversing arrays with the square of for in

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

4, With for in, you can operate not only 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 is added, which is easy to use

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


      let s = "helloabc"; 
      for(let c of s) {  
          console.log(c); 
     }

In summary, for in always gets the subscript of a key or array or string, while for of, like forEach, gets the value directly
Result for of cannot be used by object
For the new Map,Set the

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

Detailed summary of javascript traversal object

1. Native javascript traversal

(1) for loop traversal

let array1 = ['a','b','c'];
for (let i = 0;i < array1.length;i++){
  console.log(array1[i]);  // a  b  c 
}

(2) JavaScript provides foreach() map() two ways to traverse Array objects

forEach is similar to map in that it can traverse every element of an array with the same parameters

Array.forEach(function(value , index , array){ //value is the current element traversed, index is the current index, and array is the array being operated
  //do something
},thisArg)      //thisArg is the value of this when the callback is executed

Difference:

The forEach() method performs the supplied function once for each element of the array. Always return undefined;

The map() method creates a new array, the result of which is the result of each element in the array calling a supplied function. The return value is a new array;

Examples are as follows:

var array1 = [1,2,3,4,5];
 
var x = array1.forEach(function(value,index){
 
    console.log(value);   //Traversal to all array elements
 
    return value + 10
});
console.log(x);   //Undefined anyway, always return undefined
 
var y = array1.map(function(value,index){
 
    console.log(value);   //Traversal to all array elements
 
    return value + 10
});
console.log(y);   //[11, 12, 13, 14, 15] returns a new array

For an array like structure, you can convert it to an array first, and then traverse it

let divList = document.querySelectorAll('div');   //divList is not an array, but a nodeList
 
//Traverse after conversion
[].slice.call(divList).forEach(function(element,index){
  element.classList.add('test')
})
 
 
Array.prototype.slice.call(divList).forEach(function(element,index){
  element.classList.remove('test')
})
 
[...divList].forEach(function(element,index){   //< strong > ES6 < / strong >
  //do something
})

(3)for ··· in ···     /      for ··· of ···

for...in statement traverses the enumerable properties of an object in any order. For each different property, the statement is executed. Each iteration is assigned a property name

Add: because the order of iterations depends on the execution environment, array traversal does not necessarily access elements in order. Therefore, when iterating the arrays with important access order, the integer index is used for Cycle (or use Array.prototype.forEach() Or for...of Cycle).

let array2 = ['a','b','c']
let obj1 = {
  name : 'lei',
  age : '16'
}
 
for(variable  in array2){   //variable is index
  console.log(variable )   //0 1 2
}
 
for(variable  in obj1){   //variable is the property name
  console.log(variable)   //name age
}

ES6 adds Iterator mechanism to provide uniform access mechanism for different data structures. As long as the data structure of Iterator is deployed, you can use for... Of... To complete the traversal operation http://es6.ruanyifeng.com/#docs/iterator )Each iteration assigns a property value

The native data structure with Iterator interface is as follows:

Array Map Set String TypedArray function's arguments object NodeList object

let array2 = ['a','b','c']
let obj1 = {
  name : 'lei',
  age : '16'
}
 
for(variable  of array2){   //< strong > variable is value < / strong >
  console.log(variable )   //'a','b','c'
}
 
for(variable  of obj1){  //< strong > common objects cannot be used in this way < / strong >
  console.log(variable)   // Error: main.js: 11uncaught typeerror: obg1 [symbol. Iterator] is not a function
}<br><br>let divList = document.querySelectorAll('div');<br><br>for(element of divlist){  //Can traverse all div nodes < br > / / do something < br >}

How can ordinary objects be traversed with for of?   http://es6.ruanyifeng.com/#docs/iterator It's detailed in a book!

In addition to the attribute name and value assigned during iteration, there are other differences between for in and for of (MDN document: https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Statements/for...of)

The for...in loop traverses all enumerable properties of an object.

for...of traverses data structures with iterator interface

for...in traverses each property name (on the current object and its prototype), while for...of traverses each property value (on the current object)

Object.prototype.objCustom = function () {};
Array.prototype.arrCustom = function () {};
 
let iterable = [3, 5, 7];
iterable.foo = "hello";
 
for (let i in iterable) {
  console.log(i); // logs 0, 1, 2, "foo", "arrCustom", "objCustom"
}
 
for (let i of iterable) {
  console.log(i); // logs 3, 5, 7
}

Article from: https://www.cnblogs.com/amujoe/p/8875053.html

Topics: Javascript Attribute