ES6 for in the for of use and differences of

   // for in traversal is the index of the array (ie, keys), while for of traverse is an array element value.
 let arr = [1,2,3,4,5,6,7]
    for(let index of arr){
     //   console.log(index)//1 2 3 4 5 6 7
        
    }
    for(let index in arr){
       // console.log(index)//0 1 2 3 4 5 6
        //console.log(arr)//1 2 3 4 5 6 7
        //console.log(arr[index])
    }
    // traverse the object is usually used for in the keys to traverse the object
    let obj = {
        a:1,
        b:2,
        c:3
    }
    for(let key in obj){
        console.log(key)//a b c 
        //console.log(obj[key])//1 2 3
    }

forEach

  1. Three parameters, a first value, the second index, the third array thereof.
  2. It applies to an array, set, map, not suited to the string, Object.
  3. You can not modify and delete data collections, for the same efficiency and recycling, do not care about the next set of target returns.
  4. You can not terminate the loop, break, continue not be used.
    chestnut:
    let arr = [1, "ding", null, 5, true, undefined];
    arr.forEach(function (value, index, a) {
        console.log("value:", value, "index:", index, "a:", a);
    })
 

for in

  1. Index to a string
  2. Used for traversing the object, json, arrays, no order, increasing the conversion process so overhead is relatively large
  3. Can be extended attributes will traverse
  4. Support break, continue
    chestnuts:
 for (let item in obj) {
        console.log(item, ":", obj[item]);
        if (item == "age") delete obj [item]; // delete attribute success
    }
    console.log("obj:", obj);
 
  1. Is the best way through the array, may be used in the set, map, array type, the string, but does not support native Object traversal.
  2. Support break, continue


Guess you like

Origin www.cnblogs.com/manban/p/12217961.html