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.
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 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: mean?)
for ... 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
@@ 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!