Home  >  Article  >  Web Front-end  >  Detailed explanation of ES6 iterable protocol and iterator protocol

Detailed explanation of ES6 iterable protocol and iterator protocol

小云云
小云云Original
2018-01-15 09:10:071572browse

This article mainly introduces the iterable protocol and iterator protocol of ES6 syntax in detail. The editor thinks it is quite good, so I will share it with you now and give it as a reference. Let’s follow the editor to take a look, I hope it can help everyone.

Several additions to ECMAScript 2015 are not new built-ins or syntax, but protocols. These protocols can be implemented by any object that follows certain conventions.
There are two protocols: iterable protocol and iterator protocol.

Iterable protocol

The iterable protocol allows JavaScript objects to define or customize their iteration behavior, for example (defined) in a for. What values ​​in the .of structure can be looped (obtained). Some built-in types are built-in iterable objects and have default iteration behavior, such as Array or Map, while other types are not (such as Object).

The purpose of the Iterator interface is to provide a unified access mechanism for all data structures, that is, a for...of loop (see below for details). When using a for...of loop to traverse a certain data structure, the loop will automatically look for the Iterator interface, call the Symbol.iterator method, and return the default iterator of the object.

ES6 stipulates that the default Iterator interface is deployed in the Symbol.iterator property of the data structure. In other words, as long as a data structure has the Symbol.iterator property, it can be considered "iterable" (iterable). The Symbol.iterator property itself is a function, which is the default iterator generation function of the current data structure. Executing this function will return a traverser.

In order to become an iterable object, an object must implement (or an object in its prototype chain) must have a property named Symbol.iterator:

Iterator protocol

The iterator protocol defines a standard way to produce a finite or infinite sequence of values.

JavaScript’s original data structures representing “collections” are mainly arrays (Array) and objects (Object). ES6 adds Map and Set. In this way, there are four types of data collections, and users can use them in combination to define their own data structures. For example, the members of an array are Maps, and the members of Maps are objects. This requires a unified interface mechanism to handle all different data structures.

Iterator (Iterator) is such a mechanism. It is an interface that provides a unified access mechanism for various different data structures. As long as any data structure deploys the Iterator interface, it can complete the traversal operation (that is, process all members of the data structure in sequence).

Iterator has three functions: first, it provides a unified and simple access interface for various data structures; second, it enables the members of the data structure to be arranged in a certain order; third, ES6 creates a A new traversal command for...of loop, the Iterator interface is mainly used for for...of consumption.

The traversal process of Iterator is like this.

  1. Create a pointer object pointing to the starting position of the current data structure. In other words, the traverser object is essentially a pointer object.

  2. The first time you call the next method of a pointer object, you can point the pointer to the first member of the data structure.

  3. The second time you call the next method of the pointer object, the pointer points to the second member of the data structure.

  4. Continuously call the next method of the pointer object until it points to the end of the data structure.

Every time the next method is called, the information of the current members of the data structure will be returned. Specifically, it returns an object containing two properties: value and done. Among them, the value attribute is the value of the current member, and the done attribute is a Boolean value indicating whether the traversal has ended.


var someString = "hi";
typeof someString[Symbol.iterator]; // "function"
var iterator = someString[Symbol.iterator]();
iterator + "";  // "[object String Iterator]"
iterator.next()    // { value: "h", done: false }
iterator.next();   // { value: "i", done: false }
iterator.next();   // { value: undefined, done: true }

The native data structure with Iterator interface is as follows.

  1. Array

  2. Map

  3. ##Set

  4. String

  5. ##TypedArray
  6. arguments object of function
  7. NodeList object
  8. Note that objects do not have an Iterator interface. If an object wants to have an Iterator interface that can be called by a for...of loop, it must deploy the traverser generation method (prototype) on the Symbol.iterator property. Objects on the chain can also have this method).

Occasions when calling the Iterator interface


There are some occasions where the Iterator interface (i.e. Symbol.iterator method) will be called by default, except for the for... .of loop, destructuring assignment, and spread operator will actually call the default Iterator interface.

In fact, this provides a simple mechanism to convert any data structure deployed with the Iterator interface into an array. In other words, as long as a data structure deploys the Iterator interface, you can use the spread operator on it to convert it into an array.

Since array traversal will call the traverser interface, any occasion that accepts an array as a parameter actually calls the traverser interface. Here are some examples.

    for...of
  1. Array.from()
  2. Map(), Set(), WeakMap(), WeakSet() (such as new Map([['a',1],['b',2]]))
  3. Promise.all ()
  4. Promise.race()

for...of

for...of 循环是最新添加到 JavaScript 循环系列中的循环。

它结合了其兄弟循环形式 for 循环和 for...in 循环的优势,可以循环任何可迭代(也就是遵守可迭代协议)类型的数据。默认情况下,包含以下数据类型:String、Array、Map 和 Set,注意不包含 Object 数据类型(即 {})。默认情况下,对象不可迭代。

在研究 for...of 循环之前,先快速了解下其他 for 循环,看看它们有哪些不足之处。

for 循环

for 循环的最大缺点是需要跟踪计数器和退出条件。我们使用变量 i 作为计数器来跟踪循环并访问数组中的值。我们还使用 Array.length 来判断循环的退出条件。

虽然 for 循环在循环数组时的确具有优势,但是某些数据结构不是数组,因此并非始终适合使用 loop 循环。

for...in 循环

for...in 循环改善了 for 循环的不足之处,它消除了计数器逻辑和退出条件。但是依然需要使用 index 来访问数组的值.

此外,当你需要向数组中添加额外的方法(或另一个对象)时,for...in 循环会带来很大的麻烦。因为 for...in 循环循环访问所有可枚举的属性,意味着如果向数组的原型中添加任何其他属性,这些属性也会出现在循环中。这就是为何在循环访问数组时,不建议使用 for...in 循环。

注意: forEach 循环 是另一种形式的 JavaScript 循环。但是,forEach() 实际上是数组方法,因此只能用在数组中。也无法停止或退出 forEach 循环。如果希望你的循环中出现这种行为,则需要使用基本的 for 循环。

for...of 循环

for...of 循环用于循环访问任何可迭代的数据类型。


const digits = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];

for (const digit of digits) {
 console.log(digit);
}

可以随时停止或退出 for...of 循环。


const digits = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];

for (const digit of digits) {
 if (digit % 2 === 0) {
  continue;
 }
 console.log(digit); //1,3,5,7,9
}

不用担心向对象中添加新的属性。for...of 循环将只循环访问对象中的值。

相关推荐:

实例分享PHP迭代器接口Iterator用法分析

调整JavaScript抽象的迭代方案

JavaScript数组的5种迭代方法实例详解


The above is the detailed content of Detailed explanation of ES6 iterable protocol and iterator protocol. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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