Understanding for...of loops and Iterable objects in ES6
Recommended tutorial: "JavaScript Video Tutorial"
This article will study the for... of
loop of ES6. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.
Old Method
In the past, there were two ways to traverse javascript.
The first is the classic for i
loop, which allows you to iterate over an array or any object that is indexable and has a length
property.
for(i=0;i<things.length;i++) { var thing = things[i] /* ... */ }
Followed by for ... in
loop, used to loop through the key/value pairs of an object.
for(key in things) { if(!thing.hasOwnProperty(key)) { continue; } var thing = things[key] /* ... */ }
for ... in
The loop is often seen as an aside because it loops over each enumerable property of the object. This includes properties of the parent object in the prototype chain, as well as all properties assigned to methods. In other words, it goes through some things that people might not expect. Using for ... in
usually means a lot of guard clauses in the loop block to avoid unwanted attributes.
Early JavaScript solved this problem through libraries. Many JavaScript libraries (eg: Prototype.js, jQuery, lodash, etc.) have utility methods or functions like each
or foreach
that allow you to do it without for i
or for ... in
Loop through objects and arrays.
for ... of
Loops are ES6's way of trying to solve some of these problems without third-party libraries.
for … of
##for ... of Loop
for(const thing of things) { /* ... */ }
iterable ( iterable)Object.
An iterable object is an object that defines the@@ iterator method, and the @@iterator method returns an object that implements the iterator protocol object, or the method is a generator function.
You need to understand a lot of things in this sentence:- Iterable object
- @@iteratorMethod (What does @@
mean?)
- Iterator Protocol (What does the protocol here mean?) Wait, iterate (iterable) and iterator (iterator) are not the same thing? In addition, what the hell is a generator function?
Built-in Iterable
First of all, some built-in objects in JavaScript objects can naturally be iterated. For example, the easiest thing to think of is the array object. Arrays can be used in afor ... of loop as in the following code:
const foo = [ 'apples','oranges','pears' ] for(const thing of foo) { console.log(thing) }
apples oranges pears
entries method of array, which returns an iterable object. This iterable returns the key and value on each iteration. For example, the following code:
const foo = [ 'apples','oranges','pears' ] for(const thing of foo.entries()) { console.log(thing) }
[ 0, 'apples' ] [ 1, 'oranges' ] [ 2, 'pears' ]
entries method will be more useful when using the following syntax
const foo = [ 'apples','oranges','pears' ] for(const [key, value] of foo.entries()) { console.log(key,':',value) }
Two variables are declared in the loop: one for returning the first item of the array (the key or index of the value), and the other for the second item (the value that the index actually corresponds to).
A normal javascript object isnot iterable. If you execute the following code:
// 无法正常执行 const foo = { 'apples':'oranges', 'pears':'prunes' } for(const [key, value] of foo) { console.log(key,':',value) }
$ node test.js /path/to/test.js:6 for(const [key, value] of foo) { TypeError: foo is not iterable
HoweverglobalObject static
entries The method accepts a normal object as a parameter and returns an
iterable object. A program like this:
const foo = { 'apples':'oranges', 'pears':'prunes' } for(const [key, value] of Object.entries(foo)) { console.log(key,':',value) }
$ node test.js apples : oranges pears : prunes
Create your own Iterable
If you want to create your own Iterable Iterating objects takes more time. You'll remember what I said earlier: An iterable object is an object that defines the@@ iterator method, and the @@iterator method returns an implementation of An object of the iterator protocol , or the method is a generator function.The easiest way to understand these contents is to create an iterable object step by step. First, we need an object that implements the
@@iterator method. The @@ notation is a bit misleading, what we really want to do is define the method using the predefined
Symbol.iterator symbol.
const foo = { [Symbol.iterator]: function() { } } for(const [key, value] of foo) { console.log(key, value) }
for(const [key, value] of foo) { ^ TypeError: Result of the Symbol.iterator method is not an object
Symbol. iterator method, but the result
of the call is not an object.
iterator protocol. This means that the iterator method needs to return an object with the next key, and the
next key is a function.
const foo = { [Symbol.iterator]: function() { return { next: function() { } } } } for(const [key, value] of foo) { console.log(key, value) }
for(const [key, value] of foo) { ^ TypeError: Iterator result undefined is not an object
这次 javascript 告诉我们它试图调用 Symbol.iterator
方法,而该对象的确是一个对象,并且实现了 next
方法,但是 next
的返回值不是 javascript 预期的对象。
next
函数需要返回有特定格式的对象——有 value
和 done
这两个键。
next: function() { //... return { done: false, value: 'next value' } }
done
键是可选的。如果值为 true
(表示迭代器已完成迭代),则说明迭代已结束。
如果 done
为 false
或不存在,则需要 value
键。 value
键是通过循环此应该返回的值。
所以在代码中放入另一个程序,它带有一个简单的迭代器,该迭代器返回前十个偶数。
class First20Evens { constructor() { this.currentValue = 0 } [Symbol.iterator]() { return { next: (function() { this.currentValue+=2 if(this.currentValue > 20) { return {done:true} } return { value:this.currentValue } }).bind(this) } } } const foo = new First20Evens; for(const value of foo) { console.log(value) }
生成器
手动去构建实现迭代器协议的对象不是唯一的选择。生成器对象(由生成器函数返回)也实现了迭代器协议。上面的例子用生成器构建的话看起来像这样:
class First20Evens { constructor() { this.currentValue = 0 } [Symbol.iterator]() { return function*() { for(let i=1;i<=10;i++) { if(i % 2 === 0) { yield i } } }() } } const foo = new First20Evens; for(const item of foo) { console.log(item) }
本文不会过多地介绍生成器,如果你需要入门的话可以看这篇文章。今天的重要收获是,我们可以使自己的 Symbol.iterator
方法返回一个生成器对象,并且该生成器对象能够在 for ... of
循环中“正常工作”。 “正常工作”是指循环能够持续的在生成器上调用 next
,直到生成器停止 yield
值为止。
$ node sample-program.js 2 4 6 8 10
原文地址:https://alanstorm.com/es6s-many-for-loops-and-iterable-objects/
作者:Alan Storm
译文地址:https://segmentfault.com/a/1190000023924865
更多编程相关知识,请访问:编程学习网站!!
The above is the detailed content of Understanding for...of loops and Iterable objects in ES6. 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











How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

JavaScript is a programming language widely used in web development, while WebSocket is a network protocol used for real-time communication. Combining the powerful functions of the two, we can create an efficient real-time image processing system. This article will introduce how to implement this system using JavaScript and WebSocket, and provide specific code examples. First, we need to clarify the requirements and goals of the real-time image processing system. Suppose we have a camera device that can collect real-time image data
