1. The for… The of loop can replace the forEach method of an array instance

const arr = ['red', 'green', 'blue']; arr.forEach((item,index)=> { console.log(item); // red green blue console.log(index); // 0 1 2});Copy the code

2.JavaScript’s original for… In loop, can only get the key name of the object, not the key value directly. ES6 provided for… The of loop, which allows traversal to obtain key values

var arr = ['a', 'b', 'c', 'd'];

for (let i in arr) {
  console.log(i); // 0 1 2 3
}

for (let i of arr) {
  console.log(i); // a b c d
}
Copy the code

3. The for… The of loop calls the traverser interface, which returns only properties with numeric indexes.

let arr = [3, 5, 7]; arr.foo = 'hello'; for (let i in arr) { console.log(i); // "0", "1", "2", "foo" } for (let i of arr) { console.log(i); // "3", "5", "7"}Copy the code

4. The for… The of loop correctly recognizes 32-bit UTF-16 characters.

for (let x of 'a\uD83D\uDC0A') {
  console.log(x);
}
// 'a'
// '\uD83D\uDC0A'
Copy the code

The difference between

The for… Disadvantages of the IN loop (for in loop object) – for in always gets the key or array of objects, the subscript of the string
  1. Array keys are numbers, but for… The in loop takes strings as keys “0”, “1”, “2”, and so on.
  2. The for… The IN loop iterates not only over numeric key names, but also over other manually added keys, even keys on the prototype chain.
  3. In some cases, for… The in loop iterates through the key names in any order.

All in all, for… The in loop is designed primarily for traversing objects, not for traversing groups of numbers.

The for… The advantage of the of function (for of array) – for of, like forEach, gets the value directly
  1. Has the same for… Same concise syntax as in, but without for… In those shortcomings.
  2. Unlike the forEach method, it can be used with break, continue, and return.
  3. Provides a unified operation interface for traversing all data structures.