When iterating over data in a loop statement, a variable must be initialized to record the position of each iteration in the data set, and in many programming languages, iterator objects have been used programmatically to return each element of the set during the iteration

The use of iterators can greatly simplify data manipulation, so ES6 has added this iterator feature to JS. New array methods and new collection types (such as sets and maps) rely on iterators. This new feature is essential for efficient data processing, and iterators are present in many other language features: new for-of loops, expansion operators (…) Even asynchronous programming can use iterators

Example:

Here is a standard for loop that tracks the index of the Colors array through variable I, incrementing each time the loop is executed if I is less than len, and executing the next loop

var colors = ["red", "green", "blue"];
for (var i = 0, len = colors.length; i < len; i++) {
    console.log(colors[i]);
}
Copy the code

Although the loop syntax is simple, if multiple loops are nested and you need to track multiple variables, the code complexity can be greatly increased, and you can accidentally use trace variables from other for loops, which can lead to errors in your program. Iterators are designed to eliminate this complexity and reduce errors in loops

The Iterator Iterator

Iterators are special objects with proprietary interfaces designed for the iterative process. All iterator objects have a next() method that returns a result object each time it is called. The result object has two attributes: value, which represents the next value to be returned; The other is done, which is a Boolean value that returns true if there is no more data to return. The iterator also holds an internal pointer to the location of the value in the current collection, and each time the next() method is called, the next available value is returned

If the next() method is called after the last value is returned, the value of done in the returned object will be true, and the value will contain the final value returned by the iterator. This return value is not part of the data set. It is similar to the return value of a function, and is the last method to pass information to the caller during the function call. Return undefined if there is no relevant data

The result object is as follows:

{value: // value, done: // Boolean, indicating whether it is finished}Copy the code

Encapsulate an iterator.

Function createIterfator(arr) {var I = 0; Var done = (I => arr.length); var done = (I => arr.length); var value =! done ? arr[i++]:undefined; Return {done, value}}}} var Iterator=createIterfator([1,2,3,4]); console.log(Iterator.next()); // "{ value: 1, done: false }" console.log(Iterator.next()); // "{ value: 2, done: false }" console.log(Iterator.next()); // "{ value: 3, done: false }" console.log(Iterator.next()); // "{value: 4, done: false}" // all calls after console.log(iterator.next ()); // "{ value: undefined, done: true }"Copy the code

The Generator Generator

A generator is a function that returns an iterator, denoted by an asterisk (*) after the function keyword. The new keyword yield is used in the function. The asterisk can be next to the function keyword, or you can add a space in the middle.

Function *createIterator() {yield 1; yield 2; yield 3; } // Generators can be called like normal functions, but will return an iterator let iterator = createIterator(); console.log(iterator.next().value); // 1 console.log(iterator.next().value); // 2 console.log(iterator.next().value); / / 3Copy the code

In this example, the asterisk before createlterator() indicates that it is a generator; The yield keyword is also a new feature in ES6 that allows you to specify the return value and the order in which the iterator’s next() method is called. After generating the iterator, three consecutive calls to its next() method return three different values, 1, 2, and 3. A generator is called just like any other function, eventually returning a created iterator

The most interesting part of a generator function is that it automatically stops execution each time a yield statement is executed. For example, in the above code, after the yield 1 statement is executed, the function does not execute any other statements until the next() method of the iterator is called again. This ability of generator functions to abort function execution has many interesting applications

  • The yield keyword can only be used within a generator. Using it elsewhere will cause the program to throw an error
  • Generators can also be created using function expressions by adding an asterisk (*) between the function keyword and the parentheses. You cannot create generators using arrow functions
  • Because generators are functions themselves, they can be added to objects. For example, in es5-style object literals, generators can be created through function expressions
  • A common function of generators is to generate state machines
  1. iterable
  • You can access the default iterator of an object through symbol. iterator
  • By default, objects defined by developers are non-iterable, but they can be made iterable by adding a generator to the symbol. iterator property
  • By using the expansion operator (…) You can convert a Set to an array
  1. Built-in iterators
  • Collection object iterator

There are three types of Set objects in ES6: array, Map, and Set

To better access the contents of the objects, each of the three types of iterators is built in

Entries () returns an iterator of multiple keys to values() and keys() of the set. Keys () returns an iterator of all the keys in the setCopy the code

② The default iterator ** for different collection types

Each collection type has a default iterator, which is used in for-of loops if not explicitly specified. The default iterator for arrays and sets is the values() method, and the default iterator for Map is the entries() method. With these default iterators, it is much easier to use collection objects in for-of loops

  • ES5 officially states that characters in a string can be accessed through square brackets (that is, text[0] can get the first character of the string text, and so on). Because square brackets operate on encoding units rather than characters, double-byte characters cannot be accessed properly
  • 【NodeList iterator 】