Home >Web Front-end >JS Tutorial >Detailed explanation of for...of loops and iterable objects in ES6

Detailed explanation of for...of loops and iterable objects in ES6

青灯夜游
青灯夜游forward
2020-12-08 17:56:143134browse

Detailed explanation of for...of loops and iterable objects in ES6

This article will study ES6’s for ... of loops.

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 viewed as an aside because it loops through 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 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)
}

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

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

will output the following

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

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

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

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 = {
  &#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)
}

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 object, you need to spend 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

This time javascript tells us that it is trying to call the Symbol.iterator method, and the object is indeed an object and implements next method, but the return value of next is not the object expected by javascript.

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

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

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<=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

更多编程相关知识,请访问:编程视频!!

The above is the detailed content of Detailed explanation of 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.com. If there is any infringement, please contact admin@php.cn delete