ES6 iterators and for.of loops (detailed tutorial)
This article mainly introduces the learning summary of ES6 iterator (Iterator) and for.of loop usage. Now I will share it with you and give you a reference.
1. What is an iterator?
The generator concept is available in Java, Python and other languages, and ES6 has also been added to JavaScript. Iterator allows us to avoid the need to initialize the collection and index variables. Instead, we use the next method of the iterator object to return the value of the next item in the collection, which is biased toward programming.
Iterators are objects with special interfaces. Contains a next() method. The call returns an object containing two attributes, namely value and done. Value represents the value of the current position, and done represents whether the iteration is complete. When it is true, calling next is invalid.
Traversing collections in ES5 usually uses a for loop. Arrays also have forEach methods, and objects are for-in. Map and Set are added in ES6, and iterators can handle all collection data in a unified way. Iterator is an interface. As long as your data structure exposes an iterator interface, iteration can be completed. ES6 created a new traversal command for...of loop, and the Iterator interface is mainly used for consumption by for...of.
2. How to use iterators?
1. Default Iterator interface
Data structure As long as the Iterator interface is deployed, we will make this data structure "traversable" ( Iterable). ES6 stipulates that the default Iterator interface is deployed in the Symbol.iterator property of the data structure. In other words, as long as a data structure has Symbol.iterator data, it can be considered "traversable" (iterable).
Native data structure that can be consumed by for...of
Array
Map
Set
String
TypedArray (a generic fixed-length buffer type that allows reading from the buffer Binary data)
The arguments object in the function
NodeList object
can be seen above There is no object (Object) in the native data structure. Why?
That’s because the order of traversal of object properties is uncertain and needs to be specified manually by the developer. In essence, the traverser is a linear process. For any non-linear data structure, deploying the traverser interface is equivalent to deploying a linear transformation.
Do the following processing to make the object available for consumption by for...of:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
|
2. When the Iterator interface is called
(1) Destructuring assignment
1 2 3 4 5 6 |
|
(2) Extension operator
1 2 3 4 5 6 7 8 |
|
(3) Yield* expression in the Generator function (introduced in the next chapter)
1 2 3 4 5 6 7 8 9 10 11 12 13 |
|
(4) Others Occasion
for..of
Array.from
Map(), Set( ), WeakMap(), WeakSet()
Promise.all()
- ##Promise.race()
3. Advantages of for...of loop
Let’s first look at the disadvantages of the array forEach method:1 2 3 4 |
|
1 2 3 |
|
- The key name of the array is a number, but the for...in loop is based on Strings as key names, "0", "1", "2", etc.
- The for...in loop can not only traverse numeric key names, but also traverse manually added period recommendations, even keys on the prototype chain.
- In some cases, the for...in loop session traverses the key names in any order
- for...in traversal is mainly for Designed for traversing objects, not suitable for traversing arrays
- Has the same concise syntax as for...in, but does not have the shortcomings of for...in
- Different from the forEach method, It can be used with break, continue and return
- Provides a unified operation interface for traversing all data structures
1 2 3 4 5 6 |
|
4, How to use for...of loop for each data type?
(1) Arrayfor...of loop allows traversing the array to obtain key values1 2 3 4 5 6 7 |
|
1 2 3 4 5 6 7 8 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
|
1 2 3 4 5 6 7 8 9 10 11 12 |
|
1 2 3 4 |
|
1 2 3 4 5 6 7 8 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
|
三、迭代器应用实例
1、斐波那契数列
下面我们就使用迭代器来自定义自己的一个斐波那契数列组,我们直到斐波那契数列有两个运行前提,第一个前提是初始化的前两个数字为0,1,第二个前提是将来的每一个值都是前两个值的和。这样我们的目标就是每次都迭代输出一个新的值。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
|
2、任务队列迭代器
我们可以定义一个任务队列,该队列初始化时为空,我们将待处理的任务传递后,传入数据进行处理。这样第一次传递的数据只会被任务1处理,第二次传递的只会被任务2处理… 代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 |
|
3、延迟执行
假设我们有一个数据表,我们想按大小顺序依次的获取数据,但是我们又不想提前给他排序,有可能我们根本就不去使用它,所以我们可以在第一次使用的时候再排序,做到延迟执行代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
|
上面是我整理给大家的,希望今后会对大家有帮助。
相关文章:
The above is the detailed content of ES6 iterators and for.of loops (detailed tutorial). 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 iterators and recursive algorithms to process data in C# requires specific code examples. In C#, iterators and recursive algorithms are two commonly used data processing methods. Iterators can help us traverse the elements in a collection, and recursive algorithms can handle complex problems efficiently. This article details how to use iterators and recursive algorithms to process data, and provides specific code examples. Using Iterators to Process Data In C#, we can use iterators to iterate over the elements in a collection without knowing the size of the collection in advance. Through the iterator, I

async is es7. async and await are new additions to ES7 and are solutions for asynchronous operations; async/await can be said to be syntactic sugar for co modules and generator functions, solving js asynchronous code with clearer semantics. As the name suggests, async means "asynchronous". Async is used to declare that a function is asynchronous; there is a strict rule between async and await. Both cannot be separated from each other, and await can only be written in async functions.

For browser compatibility. As a new specification for JS, ES6 adds a lot of new syntax and API. However, modern browsers do not have high support for the new features of ES6, so ES6 code needs to be converted to ES5 code. In the WeChat web developer tools, babel is used by default to convert the developer's ES6 syntax code into ES5 code that is well supported by all three terminals, helping developers solve development problems caused by different environments; only in the project Just configure and check the "ES6 to ES5" option.

In es5, you can use the for statement and indexOf() function to achieve array deduplication. The syntax "for(i=0;i<array length;i++){a=newArr.indexOf(arr[i]);if(a== -1){...}}". In es6, you can use the spread operator, Array.from() and Set to remove duplication; you need to first convert the array into a Set object to remove duplication, and then use the spread operator or the Array.from() function to convert the Set object back to an array. Just group.

In es6, the temporary dead zone is a syntax error, which refers to the let and const commands that make the block form a closed scope. Within a code block, before a variable is declared using the let/const command, the variable is unavailable and belongs to the variable's "dead zone" before the variable is declared; this is syntactically called a "temporary dead zone". ES6 stipulates that variable promotion does not occur in temporary dead zones and let and const statements, mainly to reduce runtime errors and prevent the variable from being used before it is declared, resulting in unexpected behavior.

Golang is a fast and efficient statically compiled language. Its concise syntax and powerful performance make it very popular in the field of software development. In Golang, iterator (Iterator) is a commonly used design pattern for traversing elements in a collection without exposing the internal structure of the collection. This article will introduce in detail how to implement and use iterators in Golang, and help readers better understand through specific code examples. 1. Definition of iterator In Golang, iterator usually consists of an interface and implementation

Best Practices for Iterators in PHP Programs Iterator is a very common design pattern in PHP programming. By implementing the iterator interface, we can traverse the elements in a collection object, and we can also easily implement our own iterator object. In PHP, the iterator pattern can help us operate collection objects such as arrays and lists more efficiently. In this article, we will introduce the best practices for iterators in PHP programs, hoping to help PHP developers who are also working on iterator applications. 1. Use the standard iterator interface P

How to use the next() function in Python to get the next element of an iterator. Iterator is a very commonly used concept in Python, which allows us to traverse a data collection in a specific order. During the iteration process, we often need to obtain the next element of the iterator. In this case, we can use the next() function to achieve this. In Python, we can use the iter() function to convert an iterable object into an iterator. For example, if we have a list, we can convert it into an iterator
