There are many ways to iterate over data in ECMAscript. The first is the basic for loop, which is suitable for iterating over ordinary arrays. And then for… In is good for iterating over key and value pairs; Then there are some functional traversal methods, such as the forEach method for array objects. These various ways of traversing the data all have certain limitations, so ES2015 it borrowed from many other languages to introduce a new for… Of circulation. This loop will be used as a unified way to traverse all data structures. In other words, as long as you understand for… The inner workings of OF allow you to use this loop to traverse any custom data structure.

const arr = [100, 200, 300, 400];
for (const item of arr) {
    console.log(item)
}
Copy the code
  • for … of VS for … In: the former iterates over the items of the array, while the latter iterates over the indices of the array.

  • for … Arr. ForEach (), arr. Every (), arr.

  • In addition to data can be used for… In addition to traversal of, pseudo-arrays can also use for… Of traverses, such as arguments objects, DOM node lists, set objects, and Map objects

    const s = new Set([‘foo’, ‘bar’]); for (const item of s) { console.log(item) } // foo bar const m = new Map() m.set(‘foo’, ‘123’) m.set(‘bar’, ‘456’) for (const item of m) { console.log(item) } // [‘foo’, ‘123’] // [‘bar’, ‘456’] const obj = { foo: ‘123’, bar: ‘456’, } for (const item of obj) { console.log(item) } // obj is not iterable