search
HomeWeb Front-endJS TutorialUnderstanding for...of loops and Iterable objects in ES6

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><p>Followed by <code>for ... in</code> loop, used to loop through the key/value pairs of an object. </p>
<pre class="brush:php;toolbar:false">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) {
    /* ... */
}
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 = [
'apples','oranges','pears'
]

for(const thing of foo) {
  console.log(thing)
}
The output result is all the elements in the array.

apples
oranges
pears
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 = [
'apples','oranges','pears'
]

for(const thing of foo.entries()) {
  console.log(thing)
}
will output the following

[ 0, 'apples' ]
[ 1, 'oranges' ]
[ 2, 'pears' ]
The

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)
}
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 = {
  'apples':'oranges',
  'pears':'prunes'
}

for(const [key, value] of foo) {
  console.log(key,':',value)
}
you will get an error

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

HoweverglobalObject staticentries 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)
}
to get the output you expect:

$ 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.

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)
}
You get a new error:

for(const [key, value] of foo) {
                          ^
TypeError: Result of the Symbol.iterator method is not an object
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)
}
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

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

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

next: function() {
    //...
    return {
        done: false,
        value: 'next value'
    }
}

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)
}

生成器

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

class First20Evens {
  constructor() {
    this.currentValue = 0
  }

  [Symbol.iterator]() {
    return function*() {
      for(let i=1;i<p>本文不会过多地介绍生成器,如果你需要入门的话可以看这篇文章。今天的重要收获是,我们可以使自己的 <code>Symbol.iterator</code> 方法返回一个生成器对象,并且该生成器对象能够在 <code>for ... of</code> 循环中“正常工作”。 “正常工作”是指循环能够持续的在生成器上调用 <code>next</code>,直到生成器停止 <code>yield</code> 值为止。</p><pre class="brush:php;toolbar:false">$ 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!

Statement
This article is reproduced at:segmentfault. If there is any infringement, please contact admin@php.cn delete
Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

See all articles

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

Safe Exam Browser

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.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

DVWA

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

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools