Detailed explanation of ES6 iterable protocol and iterator protocol
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.
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.
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.
The second time you call the next method of the pointer object, the pointer points to the second member of the data structure.
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.
1 2 3 4 5 6 7 |
|
The native data structure with Iterator interface is as follows.
Array
Map
- ##Set
- String ##TypedArray
- arguments object of function
- NodeList object
- 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).
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
- Array.from()
- Map(), Set(), WeakMap(), WeakSet() (such as new Map([['a',1],['b',2]]))
- Promise.all ()
- 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 循环用于循环访问任何可迭代的数据类型。
1 2 3 4 5 |
|
可以随时停止或退出 for...of 循环。
1 2 3 4 5 6 7 8 |
|
不用担心向对象中添加新的属性。for...of 循环将只循环访问对象中的值。
相关推荐:
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











Detailed explanation of the mode function in C++ In statistics, the mode refers to the value that appears most frequently in a set of data. In C++ language, we can find the mode in any set of data by writing a mode function. The mode function can be implemented in many different ways, two of the commonly used methods will be introduced in detail below. The first method is to use a hash table to count the number of occurrences of each number. First, we need to define a hash table with each number as the key and the number of occurrences as the value. Then, for a given data set, we run

Windows operating system is one of the most popular operating systems in the world, and its new version Win11 has attracted much attention. In the Win11 system, obtaining administrator rights is an important operation. Administrator rights allow users to perform more operations and settings on the system. This article will introduce in detail how to obtain administrator permissions in Win11 system and how to effectively manage permissions. In the Win11 system, administrator rights are divided into two types: local administrator and domain administrator. A local administrator has full administrative rights to the local computer

Detailed explanation of division operation in OracleSQL In OracleSQL, division operation is a common and important mathematical operation, used to calculate the result of dividing two numbers. Division is often used in database queries, so understanding the division operation and its usage in OracleSQL is one of the essential skills for database developers. This article will discuss the relevant knowledge of division operations in OracleSQL in detail and provide specific code examples for readers' reference. 1. Division operation in OracleSQL

Detailed explanation of the remainder function in C++ In C++, the remainder operator (%) is used to calculate the remainder of the division of two numbers. It is a binary operator whose operands can be any integer type (including char, short, int, long, etc.) or a floating-point number type (such as float, double). The remainder operator returns a result with the same sign as the dividend. For example, for the remainder operation of integers, we can use the following code to implement: inta=10;intb=3;

Detailed explanation of Linux system call system() function System call is a very important part of the Linux operating system. It provides a way to interact with the system kernel. Among them, the system() function is one of the commonly used system call functions. This article will introduce the use of the system() function in detail and provide corresponding code examples. Basic Concepts of System Calls System calls are a way for user programs to interact with the operating system kernel. User programs request the operating system by calling system call functions

The modulo operator (%) in PHP is used to obtain the remainder of the division of two numbers. In this article, we will discuss the role and usage of the modulo operator in detail, and provide specific code examples to help readers better understand. 1. The role of the modulo operator In mathematics, when we divide an integer by another integer, we get a quotient and a remainder. For example, when we divide 10 by 3, the quotient is 3 and the remainder is 1. The modulo operator is used to obtain this remainder. 2. Usage of the modulo operator In PHP, use the % symbol to represent the modulus

Detailed explanation of Linux's curl command Summary: curl is a powerful command line tool used for data communication with the server. This article will introduce the basic usage of the curl command and provide actual code examples to help readers better understand and apply the command. 1. What is curl? curl is a command line tool used to send and receive various network requests. It supports multiple protocols, such as HTTP, FTP, TELNET, etc., and provides rich functions, such as file upload, file download, data transmission, proxy

Numpy is a Python scientific computing library that provides a wealth of array operation functions and tools. When upgrading the Numpy version, you need to query the current version to ensure compatibility. This article will introduce the method of Numpy version query in detail and provide specific code examples. Method 1: Use Python code to query the Numpy version. You can easily query the Numpy version using Python code. The following is the implementation method and sample code: importnumpyasnpprint(np
