js in forEach, for in, for of cycle usage Detailed

A general method to iterate:

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

Second, through the array used for in the party

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

Three, forEach

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

Fourth, the use not only for in an array, also can enumerable object manipulation

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

Fifth, the ES6, increasing the for of a cycle, is simple to use

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

      let s = "helloabc"; 

      for(let c of s) {  

      console.log(c); 

     }

 
Copy the code

 To summarize: for in subscript always get an array of key or the like, string, but for of and forEach, is directly the value of
the results for of the object can not be used
for the new out of the Map, Set above

Copy the code
    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);  
    }  
Copy the code

javascript traverse the object detailed summary

1. Native javascript traversal

(1) for loop iterates

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 () Array object may traverse two side    

    Similar forEach and usage map, can be traversed to each element of the array , and the same parameters; 

Array.forEach (function (value, index, array) {// value of the current element traversed, index to the current index, array array is operating 
  // do something 
}, thisArg) thisArg // this is the callback time value

difference:

  forEach () method performs a function provided to each element of the array. Always returns undefined;

  map () method creates a new array, the result is returned after the results of each element in the array to call a function provided. The return value is a new array;

  Examples are as follows:

Copy the code
array1 = var [1,2,3,4,5]; 
 
var X = array1.forEach (function (value, index) { 
 
    the console.log (value); // can traverse all array elements 
 
    return value + 10 
}) ; 
the console.log (X); // undefined any event, the total return undefined 
 
var Y = array1.map (function (value, index) { 
 
    the console.log (value); // can traverse all array elements 
 
    return value + 10 
}); 
the console.log (Y); // [. 11, 12 is, 13 is, 14, 15] returns a new array
Copy the code

For array-like structures, may be first converted to an array , then traverse

Copy the code
let divList = document.querySelectorAll ( 'div' ); // divList not an array, but the nodeList 
 
// performed after translation traversal 
[] .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 wording </ strong> 
  // do something 
})
Copy the code

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

for...in Traverse a statements in any order may be enumerated attribute object. For each different attributes, the statement will be executed. At each iteration, it is assigned the attribute name  

Added: because the order of iterations is dependent on the execution environment, not necessarily in order, so access to the elements array traversal. So when those iterations order to access important arrays with integer index to be  for circulating (or use  Array.prototype.forEach() or  for...of recycling).

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

 ES6 added iterator (Iterator) mechanism, to provide a unified mechanism to access different data structures. As long as the deployment data structure of Iterator may be used for ··· of ··· complete traversal (Iterator Detailed: http://es6.ruanyifeng.com/#docs/iterator), each iteration is assigned  an attribute value

 Native data structure Iterator interface includes the following:

 Array Map Set String arguments Object NodeList object TypedArray function

Copy the code
= array2 the let [ 'A', 'B', 'C'] 
the let OBJ1 = { 
  name: 'LEI', 
  Age: '16' 
} 
 
for (variable of array2) {// <strong> variable is value </ strong > 
  the console.log (variable) // 'A', 'B', 'C' 
} 
 
for (variable of OBJ1) {// <strong> Common Object not be so used </ strong> 
  the console.log (variable) // error: main.js: 11Uncaught TypeError: OBJ1 [Symbol.iterator] A function IS Not 
} <br> <br> the let divList = document.querySelectorAll ( 'div'); <br> <br> for (Element of divlist) {// div can traverse all the nodes <br> // do something <br>}
Copy the code

How ordinary objects can traverse of use for it? http://es6.ruanyifeng.com/#docs/iterator a book has details!

 

  In addition to a distribution of iteration is the attribute name, one is outside the property value, for in and for of other different (MDN Documentation: https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference /Statements/for...of)

    for ... in loop iterates through all of the enumerable object a property.

      for ... of iterator will traverse the interface has a data structure

      for...in Traversal (currently on the object and its prototype) each attribute name, for...of遍历(当前对象上的)每一个属性值

Copy the code
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
}
Copy the code

 

Guess you like

Origin www.cnblogs.com/liangxiaoji/p/11018320.html