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

Keywords: Front-end Javascript Attribute

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 (Iterator details: http://es6.ruanyifeng.com/ ා docs / Iterator). Each iteration assigns the attribute 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!

There are other differences between for in and for of (MDN document: https://developer.mozilla.org/en-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
}

Posted by dhcrusoe on Sun, 26 Apr 2020 23:54:59 -0700