Home > Web Front-end > JS Tutorial > body text

What is the usage of Javascript iterator

WBOY
Release: 2022-03-01 14:59:44
Original
2785 people have browsed it

In JavaScript, iterator is a design pattern that is used to traverse the container object, that is, to get the data in it in sequence. The iterator in js has a next() method, which will be called every time Return an object, the syntax is "next:function(){return{value,done}}".

What is the usage of Javascript iterator

The operating environment of this tutorial: Windows 10 system, JavaScript version 1.8.5, Dell G3 computer.

What is the usage of Javascript iterator

Iterator is a design pattern that can traverse container objects such as linked lists and arrays without caring about the implementation details of memory allocation of container objects. The simple understanding is that we can get the data one by one, similar to a moving pointer, but it will tell us when it will end. 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, each time Each call returns an object (result object). The result object has two properties: one is value, which represents the next value to be returned; the other is done, which is a Boolean value that is true if the last value in the sequence has been iterated to. The iterator also saves an internal pointer to point to the position of the value in the current collection. Each time the next() method is called, the next available value will be returned, similar to the structure of the object below.

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

Iteration Protocol

With the further improvement of the capabilities of the javascript language, some new data types have been added such as Map, Set, WeakMap, etc., for these different The data structure can be iterated uniformly. es6 adds 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: iterable protocol and iterator protocol.

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

Iterable protocol

To become an iterable object, an The object must implement the @@iterator method. This means that the object (or an object on its prototype chain) must have a property with the key @@iterator, which can be accessed through the constant Symbol.iterator:

Simple understanding, you want a Things can be traversed, then this thing must have an @@iterator. This property can be accessed through Symbol.iterator

What is the usage of Javascript iterator

##Iterator protocol

The iterator protocol defines a standard way to produce a sequence of values ​​(whether a finite or infinite number). When there are a limited number of values, 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:

What is the usage of Javascript iterator

Iteration process

When an object needs to be iterated (such as when it is written into a for...of loop), first, its @@iterator method will be called without parameters (the returned value at this time The structure is like this { next: function () {}}), and then use the iterator returned by this method to obtain the value to be iterated (in fact, it means continuously calling this next() method)

Iteration summary

The iteration protocol can be summarized as, for a thing to be traversed, it must satisfy the iterable protocol and the iterator protocol

Iterable protocol: This object must have @@iterator, you can Access through Symbol.iterator

Iterator protocol: It is an object. The next() function of this object returns an object. This object includes two attributes, one is value and the other is done(boolean, whether it is the last An element, value can be omitted when done is true)

That is to say, the iterator object is essentially a pointer object. Use next() of the pointer object to move the pointer.

Custom iteration

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

Traditional way of writing

let obj = {
  name: 'joel',
  adress: 'gz',
  [Symbol.iterator]: () => {
     // 这里不要用this, 因为是return fn, this 会丢失
    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(&#39;atrrs:&#39; + item + &#39;,value:&#39; + obj[item])
}
Copy after login

How to write generator function

// 为不可迭代的对象添加迭代器
let obj = {
  a: 1,
  b: 2
}
obj[Symbol.iterator] = function* () {
  let keys = Object.keys(obj);
  //取到key值的长度
  let len = keys.length;
  //定义循环变量
  let n = 0;
  //条件判断
  while (n <= len - 1) {
      yield { k: keys[n], v: obj[keys[n]] };
      n++
  }
}
//返回的是个对象的key和value
for (let { k, v } of obj) {
  console.log(k, v);
}
Copy after login
Related recommendations:

javascript learning tutorial

The above is the detailed content of What is the usage of Javascript iterator. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template