Learn javascript iterator

Learn javascript iterator

Introduction

Iterator is a design pattern that can traverse container objects such as linked lists and arrays without worrying about the implementation details of memory allocation of container objects. The simple understanding is that we can get the data one by one, like a moving pointer, but it will tell us when it ends. In this way, we can do what we need to do after getting the data.

What does an iterator look like in js

In JavaScript, an iterator is a special object. This iterator object has a next() method, and each call returns an object (result object). The result object has two attributes: one is value, which indicates the next value to be returned; the other is done, which is a Boolean value. If the last value in the sequence has been iterated, it is true. The iterator also saves an internal pointer to the position of the value in the current collection. Each call to the next() method returns the next available value, similar to the structure of the object below.

{
  next: function () {
        return {
            value:'',
            done: true / false
        }  
    }
}

Iteration Protocol

As the capabilities of the JavaScript language continue to improve, some new data types have been added, such as Map, Set, WeakMap, etc. In order to allow these different data structures to be iterated in a unified manner, es6 has added the iteration protocol.

The iteration protocol is not a new built-in implementation or syntax; it is a protocol. These protocols can be implemented by any object that follows certain conventions.

The iteration protocol is specifically divided into two protocols: the iterable protocol and the iterator protocol.

The simple understanding is that in js, any object can be traversed as long as it satisfies the iteration protocol.

Iterable Protocol

To be iterable, an object must implement the @@iterator method. This means that the object (or an object in its prototype chain) must have a property with the key @@iterator, accessible via the constant Symbol.iterator:

Simply put, if you want something to be traversable, then it must have an @@iterator, which can be accessed through Symbol.iterator

property

value

[Symbol.iterator]

A function with no arguments that returns an object that conforms to the iterator protocol.

Iterator Protocol

The iterator protocol defines a standard way to produce a sequence of values, whether finite or infinite. When the value is finite, a default return value will be returned after all values ​​have been iterated.

An object conforms to the iterator protocol only if it implements a next() method with the following semantics:

property

value

next

A function with no parameters that returns an object that should have the following two properties:

done (boolean)

The next() method must return an object with two properties: done and value. If a non-object value (such as false or undefined) is returned, an exception will be thrown ("iterator.next() returned a non-object value").

Iterative process

When an object needs to be iterated (for example, when it is written into a for...of loop), first, its @@iterator method is called without parameters ( the structure returned at this time is { next: function () { }} ), and then the iterator returned by this method is used to obtain the value to be iterated (in fact, it is just calling this next() method repeatedly)

Iteration Summary

The iteration protocol can be summarized as follows: to traverse something, it must satisfy the iterable protocol and the iterator protocol.

  • Iterable protocol: This object must have an @@iterator, which can be accessed through Symbol.iterator
  • Iterator protocol: It is an object whose next() function returns an object with two attributes: value and done (boolean, whether it is the last element. When done is true, value can be omitted).

In other words, the iterator object is essentially a pointer object. The pointer is moved through the next() method of the pointer object.

Custom Iteration

Objects do not implement iterators, so objects cannot be traversed. In order to implement object traversal, we need to implement the iterator mentioned above on the object. There are usually two ways of writing. One is the traditional way of writing, which requires you to control the internal state yourself. The other is to use the iterator of the Generator returned by the generator function to implement it. The code is as follows:

Traditional writing

let obj = {
  name: 'joel',
  adress: 'gz',
  [Symbol.iterator]: () => {
     // Don't use this here, because it is return fn, this will be lost let index = -1, atrrList = Object.keys(obj);
    const objIterator = {
      next: () => {
        let result = ''
        index++
        if (index < atrrList.length) {
          result = {
            value: atrrList[index],
            done: false
          }
        } else {
          result = {
            done: true
          }
        }
        return result
      }
    }
    return objIterator
  }
}

for (const item of obj) {
    console.log('atrrs:' + item + ',value:' + obj[item])
}

Generator function writing

// Add an iterator for a non-iterable object let obj = {
  a: 1,
  b: 2
}
obj[Symbol.iterator] = function* () {
  let keys = Object.keys(obj);
  //Get the length of the key value let len ​​= keys.length;
  //Define loop variable let n = 0;
  //Conditional judgment while (n <= len - 1) {
      yield { k: keys[n], v: obj[keys[n]] };
      n++
  }
}
//The returned value is the key and value of an object
for (let { k, v } of obj) {
  console.log(k, v);
}

For other related information such as built-in iterable objects, syntax for iterable objects, built-in APIs that accept iterable objects, etc., please click here

This is the end of this article about learning javascript iterators. For more relevant javascript iterator content, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • JavaScript design pattern iterator pattern
  • The meaning and usage of JavaScript iterators
  • JavaScript design pattern iterator pattern
  • JavaScript Array Iteration Methods
  • Detailed explanation of Javascript iterators and iterative interfaces

<<:  Linux system dual network card binding configuration implementation

>>:  How to use the Fuser command in Linux system

Recommend

Provides helpful suggestions for improving website design

<br />Scientifically Design Your Website: 23...

A brief discussion on how to learn JS step by step

Table of contents Overview 1. Clearly understand ...

Detailed explanation of CSS3 Flex elastic layout example code

1. Basic Concepts //Any container can be specifie...

Videojs+swiper realizes Taobao product details carousel

This article shares the specific code of videojs+...

CSS hacks \9 and \0 may not work for hacking IE11\IE9\IE8

Every time I design a web page or a form, I am tr...

What we can learn from Google's new UI (pictures and text)

The most significant website change in 2011 was Go...

Tutorial on Migrating Projects from MYSQL to MARIADB

Prepare the database (MySQL). If you already have...

Implementation steps for building FastDFS file server in Linux

Table of contents 1. Software Package 2. Install ...

JavaScript canvas realizes the effect of nine-square grid cutting

This article shares the specific code of canvas t...

Detailed explanation of nmcli usage in CentOS8

Common nmcli commands based on RHEL8/CentOS8 # Vi...

This article will show you what Vite does to the browser's request

Table of contents Working principle: What does th...

Summary of several common logs in MySQL

Preface: In the MySQL system, there are many diff...