ES6 -- Iterator iterator

Posted by juhl on Sat, 15 Jan 2022 15:52:36 +0100

1, The concept of Iterator

Meaning: Iterator is an interface that provides a unified access mechanism for various data structures. Any data structure can complete the operation of traversing all members of the data structure as long as the Iterator interface is deployed.

The data structure with native Iterator interface is as follows:

  • Array
  • Map
  • Set
  • String
  • Arguments object for function
  • Nodelist object of DOM
  • TypedArray

ES6 stipulates that the default iterator interface is deployed on symbol Iterator property, symbol Iterator is a built-in symbol value. The built-in symbol value can be used as the attribute of [object] to expand the behavior of the object. Symbol.iterator is an expression and must be placed in square brackets; It is essentially a function. It is the default iterator generation function of the current data structure. Executing this function will return an iterator.

Example: default Iterator interface

//Declare an array
const arr = ['hello', 'world', 'nihao']
//Execute the symbol of the array Iterator method to get the default iterator interface of the array
const iterator = arr[Symbol.iterator]() 

A data structure is said to be iteratable as long as the Iterator interface is deployed.

2, Iterative process of Iterator

**

  1. Call the iterator generation function to return a pointer object (the essence of the iterator) pointing to the starting position of the data structure
  2. The next() method of the Iterator is called for the first time. The pointer points to the first member of the data structure (the next() method is the default method of the Iterator). The return value of the next() method is an object that contains the information of the current data structure member. There are two attributes: value and done. Value corresponds to the value of the member, and done corresponds to the Boolean value. If the traversal is still in progress, the value is false, If the traversal ends, the value is true
  3. Keep calling the next() method until the pointer points to the end of the data structure

**
Example: the Iterator interface of the array calls the next method (continued from the previous example)

const arr = ['hello', 'world', 'nihao']

const iterator = arr[Symbol.iterator]() 

console.log(iterator.next())//{value: "hello", done: false}
console.log(iterator.next())//{value: "world", done: false}
console.log(iterator.next())//{value: "nihao", done: false}
console.log(iterator.next())//{value: undefined, done: true}

Note: when calling the next method after traversing all members, the value is undefined

If an Object does not have an iterator interface deployed by default, it must be in symbol Iterator generation method on iterator property.

Example: deploy the Iterator interface to banji and traverse the members in the stus array

//Declare an object
const banji = {
      name: "Ultimate class 1",
      stus: [
        'xiaoning',
        'xiaoming',
        'xiaotian',
        'knight'
      ],
      //Deploy iterator generation method
      [Symbol.iterator](){
        //Save this
        const _this = this
        //Index variable
        let index = 0
        return {
          next(){
            if(index < _this.stus.length){
              return {value: _this.stus[index++], done: false}
            }else{
              return {value: undefined, done: true}
            }
          }
        }
      }
    }
//test
    const iterator = banji[Symbol.iterator]()

    console.log(iterator.next())//{value: "xiaoning", done: false}
    console.log(iterator.next())//{value: "xiaoming", done: false}
    console.log(iterator.next())//{value: "xiaotian", done: false}
    console.log(iterator.next())//{value: "knight", done: false}
    console.log(iterator.next())//{value: undefined, done: true}

3, for... of loop

In fact, the iterator interface is mainly used for for... Of loop consumption, that is, using the for... Of loop will automatically call the symbol of the current data structure Iterator property method.

Example: directly use for... of to traverse banji (continued from the previous example)

for (let v of banji){
      console.log(v)
    }
    /*
    xiaoning
    xiaoming
    xiaotian
    knight  
    */

Other common situations of calling Iterator by default are as follows:

  • Deconstruction assignment: Deconstruction assignment for array and Set structures
  • Extension operator
  • yield *: when followed by a traversable data structure, the Iterator interface of the structure will be called
  • Any occasion that receives an array as a parameter, such as array from()

4, Summary

The main functions of Iterator are as follows:

  • Provide a unified and simple access interface for various data structures
  • Enables the members of the data structure to be arranged in a certain order
  • ES6 new traversal command for... of loop. Iterator is mainly used for for... of consumption

Reprinted from:
ECMAScript 6 getting started
Author: Ruan Yifeng
https://es6.ruanyifeng.com/#docs/iterator

Topics: ECMAScript