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.
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.
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 循环用于循环访问任何可迭代的数据类型。
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 循环将只循环访问对象中的值。
相关推荐:
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!

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.


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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Dreamweaver Mac version
Visual web development tools

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

SublimeText3 English version
Recommended: Win version, supports code prompts!