This is the 27th day of my participation in the August Genwen Challenge.More challenges in August

preface

Eat enough to write code

Today we are going to learn about JavaScript iterators.

Understand iteration

Let’s start with an understanding of iteration, the simplest iteration in JavaScript:

for (let i = 1; i <=10; i++){console.log(i);
}
Copy the code

Loops are the basis of the iteration mechanism, specifying the number of iterations and the operations to be performed in each iteration. Iteration will be carried out on an ordered set. The so-called order can be understood as all items in the set can be traversed in an established order, especially the beginning and end items are clearly defined. For example, arrays:

let arr = ['aaa'.'bbb'.'ccc'];
for (let index = 0; index < arr.length; ++index){console.log(arr[index]);
}
Copy the code

Because the array has a known length and each item is indexed, the entire array can be traversed by incrementing the index. But this loop is not ideal for executing the routine. Here’s why:

  • Do you need to know how to use data structures before you iterate
  • The traversal order is not inherent in the data structure


Iterator pattern

The Iterator pattern describes a scenario in which structures can be called iterables because they implement formal Iterable and can be consumed through iterators. Basically, you can think of an iterable as an object of collection type like an array or a collection. They all have finite elements, and all have an unambiguous traversal order.

// The elements of the array are finite
// Incrementing indexes can access each element in order
let arr = [3.2.1];
// Set elements are finite
// Each element can be accessed in insertion order
let set = new Set().add(3).add(2).add(1);
Copy the code

However, an iterable need not be a collection object, but can be another data structure that simply behaves like an array. For example, in the original count loop, the values generated in that loop are transient, but the loop itself is iterating, and both count loops and arrays have the behavior of an iterable. All of a sudden fa