SoFunction
Updated on 2025-04-03

Analysis of the usage of Iterator and for..of. in ES6

This article describes the usage of Iterator and for..of. in ES6. Share it for your reference, as follows:

Iterator and for..of..traversal

concept

An Iterator is an interface that provides a unified access mechanism for various data structures. Some data structures in JS have native Iterator interfaces. In order to better understand this concept, we can also write an Iterator ourselves.

var it = simIteractor(['hi','ES5']);
(()); //Object {value: "hi", done: false}
(()); //Object {value: "ES5", done: false}
(()); //Object {value: undefined, done: true}
function simIteractor(array){
    var nextIndex = 0;
    return{
      next: function(){
        return nextIndex <  ? {value: array[nextIndex++], done: false} : {value: undefined, done:true};
      }
    };
}

2. ES6 stipulates that the default Iterator interface is deployed in the properties of the data structure, or in other words, a data structure can have the tasks that can be traversable as long as it has properties. In ES6, there are three types of data structures that have native Iterator interfaces: arrays, some array-like objects, Sets and Map.

3. When it comes to traversable, we need to talk about the traversable method.

for...in... : for-in is designed for ordinary objects, youYou can traverse to get string type keys, so they are not suitable for array traversal

For...of... : for-of loopUsed to traverse data—such as values ​​in arrays. for-of loopYou can also traverse other collections

for-of loopNot only supports arrays, but also supports most class array objects, for example DOMNodeList.

For-of loops are alsoSupport string traversal, it traverses the string as a series of Unicode characters:

or (var chr of "abc"){
  alert(chr); //A,b,c pops up in turn}

It also supports Map and Set object traversal. If you don't know the map please seehttps:///article/, if you don't know Set please seehttps:///article/

I hope this article will be helpful to everyone's ECMAScript programming.