Table of Contents
Old Method
for … of
Built-in Iterable
Create your own Iterable
生成器
Home Web Front-end JS Tutorial Understanding for...of loops and Iterable objects in ES6

Understanding for...of loops and Iterable objects in ES6

Nov 12, 2020 pm 06:12 PM
es6 javascript

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]
    /* ... */
}
Copy after login

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]
    /* ... */
}
Copy after login

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) {
    /* ... */
}
Copy after login

It will traverse an

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?
The following will address these questions one by one.

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 a

for ... of loop as in the following code:

const foo = [
&#39;apples&#39;,&#39;oranges&#39;,&#39;pears&#39;
]

for(const thing of foo) {
  console.log(thing)
}
Copy after login

The output result is all the elements in the array.

apples
oranges
pears
Copy after login

There is also the

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 = [
&#39;apples&#39;,&#39;oranges&#39;,&#39;pears&#39;
]

for(const thing of foo.entries()) {
  console.log(thing)
}
Copy after login

will output the following

[ 0, &#39;apples&#39; ]
[ 1, &#39;oranges&#39; ]
[ 2, &#39;pears&#39; ]
Copy after login

The

entries method will be more useful when using the following syntax

const foo = [
    &#39;apples&#39;,&#39;oranges&#39;,&#39;pears&#39;
]

for(const [key, value] of foo.entries()) {
  console.log(key,&#39;:&#39;,value)
}
Copy after login

in for

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 is

not iterable. If you execute the following code:

// 无法正常执行
const foo = {
  &#39;apples&#39;:&#39;oranges&#39;,
  &#39;pears&#39;:&#39;prunes&#39;
}

for(const [key, value] of foo) {
  console.log(key,&#39;:&#39;,value)
}
Copy after login

you will get an error

$ node test.js
/path/to/test.js:6
for(const [key, value] of foo) {
TypeError: foo is not iterable
Copy after login

HoweverglobalObject staticentries The method accepts a normal object as a parameter and returns an iterable object. A program like this:

const foo = {
  &#39;apples&#39;:&#39;oranges&#39;,
  &#39;pears&#39;:&#39;prunes&#39;
}

for(const [key, value] of Object.entries(foo)) {
  console.log(key,&#39;:&#39;,value)
}
Copy after login

to get the output you expect:

$ node test.js
apples : oranges
pears : prunes
Copy after login

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.

If you define an object with an iterator method and try to iterate:

const foo = {
  [Symbol.iterator]: function() {
  }
}

for(const [key, value] of foo) {
  console.log(key, value)
}
Copy after login

You get a new error:

for(const [key, value] of foo) {
                          ^
TypeError: Result of the Symbol.iterator method is not an object
Copy after login

This is javascript telling us that it is trying to call

Symbol. iterator method, but the result of the call is not an object.

In order to eliminate this error, it is necessary to use the iterator method to return an object that implements the

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)
}
Copy after login

If you run the above code, you will get a new error.

for(const [key, value] of foo) {
                     ^
TypeError: Iterator result undefined is not an object
Copy after login

这次 javascript 告诉我们它试图调用 Symbol.iterator 方法,而该对象的确是一个对象,并且实现了 next 方法,但是 next 的返回值不是 javascript 预期的对象。

next 函数需要返回有特定格式的对象——有 valuedone 这两个键。

next: function() {
    //...
    return {
        done: false,
        value: &#39;next value&#39;
    }
}
Copy after login

done 键是可选的。如果值为 true(表示迭代器已完成迭代),则说明迭代已结束。

如果 donefalse 或不存在,则需要 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)
}
Copy after login

生成器

手动去构建实现迭代器协议的对象不是唯一的选择。生成器对象(由生成器函数返回)也实现了迭代器协议。上面的例子用生成器构建的话看起来像这样:

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)
}
Copy after login

本文不会过多地介绍生成器,如果你需要入门的话可以看这篇文章。今天的重要收获是,我们可以使自己的 Symbol.iterator 方法返回一个生成器对象,并且该生成器对象能够在 for ... of 循环中“正常工作”。 “正常工作”是指循环能够持续的在生成器上调用 next,直到生成器停止 yield 值为止。

$ node sample-program.js
2
4
6
8
10
Copy after login

原文地址: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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1268
29
C# Tutorial
1243
24
How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

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 implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

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

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

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 implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

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 forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

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

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

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

How to use insertBefore in javascript How to use insertBefore in javascript Nov 24, 2023 am 11:56 AM

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 and WebSocket: Building an efficient real-time image processing system JavaScript and WebSocket: Building an efficient real-time image processing system Dec 17, 2023 am 08:41 AM

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

See all articles