This is the fifth day of my participation in the August More text Challenge. For details, see:August is more challenging

One of the most frequently interviewed questions for many junior front end developers as they move to the middle is iterators and generators, which have been used in development but have no idea what they are, or have some knowledge of them but not enough. This article will be helpful for this part of the developer, to clarify iterators.

Earlier iterations

Iteration, of course, is simply a loop, and counting loops are one of the simplest in JavaScript. Example:

for(let i = 0; i < 9; ++i){
	console.log("[ i ]", i);
}
Copy the code

The basis of iteration is the loop, which contains several necessary conditions:

  • You can specify the number of iterations
  • You can specify the operations to be performed in each iteration
  • Each iteration is completed before the next iteration begins
  • The order is defined in advance

When you loop through an array, you iterate over an ordered set. “Ordered” means that all the elements in the array can be traversed in order from the first item to the last item. Because the array has a certain length, and each item can be indexed, that means you can use the index to traverse the entire array. Example:

const arr = ["a"."b"."c"];

for(let i = 0; i < arr.length; ++i){
	console.log(arr[i]);
}
Copy the code

However, this mode requires knowing in advance what data structure is being used, such as an array. If it is changed to another data type, or a data structure with an implicit order, then the order of traversal is not determined. The forEach() method was added to ES5. Example:

const arr = ["a"."b"."c"];

arr.forEach(item= >{
	console.log(item);
});
Copy the code

This method does not use the array index to iterate over and retrieve individual values, but it does not indicate when the iteration is over, so it only applies to array traversals. To address these issues, after ES6, JavaScript supported the iterator pattern.

Iterator pattern

The iterator pattern is a very abstract way of thinking about objects such as arrays or collections whose elements are finite and independent of each other. To quote the Little Red Book, it reads:

The Iterator pattern, especially in the context of ECMAScript, describes a scenario in which structures can be called “iterable” because they implement the formal iterable interface and can be consumed by an Iterator.

Iterator factory function

The iterator factory function, symbol.iterator (), is the default property that most built-in types contain. It exposes the Iterable interface (the Iterable protocol), meaning that in order for a data type to support iteration, it must support the Iterable protocol. ECMAScript states that the default iterator that is exposed must have “Symbol. Iterator” as the key and return a new iterator. It is also easy to check whether there is a default iterator property. Example:

const obj = {};
const arr = ["a"."b"."c"];

console.log(obj[Symbol.iterator]); // underfined
console.log(arr[Symbol.iterator]); // f values() { [native code] }

console.log(arr[Symbol.iterator]()); // ArrayIterator {}
Copy the code

, of course, is not in our actual development shows that call iterator factory function, support data types can be iterative agreement will automatically be compatible to accept object iteration of any language features, such as when we use cycle, the for -, deconstruction, extension, operator, will automatically be invoked in the background to provide object iteration of the iterator function factory, To create an iterator.

Iterator protocol

Iterator protocol convention An iterator is a one-time object. When the iterator factory function is called, it returns a next() method. This method is called every time an iteration succeeds, and it knows the value of the next iteration. The next() method returns an object with package contents properties: done and value. Done indicates whether it is possible to continue calling the next() method to get the next value, meaning whether it is “exhausted.” A Boolean value is returned. Value represents the next value of the iterable. When done is true, value is underpaid. When done is false, the call continues to the next iteration. Example:

// Iterable objects
let arr = ['foo'.'bar'];// The iterator factory function
console.log(arr[Symbol.iterator]);// f values() { [native code] }

/ / the iterator
let iter = arr[Symbol.iterator]();
console.log(iter); // ArrayIterator{}

// Perform the iteration
console.log(iter.next()); // { done: false, value: 'foo' }
console.log(iter.next()); // { done: false, value: 'bar' }
console.log(iter.next()); // { done: true, value: undefined }
Copy the code

Write in the last

With the iterator protocol, you can implement a custom iterator, such as specifying how many times the iterator can be iterated, or terminating the iteration early.

Writing is not easy. I hope I can get a “like” from you. If the article is useful to you, you can select “bookmark”. If there are any mistakes or suggestions in the article, please comment on it. Thank you. ❤ ️

Welcome to other articles

  • Internationalizing your website with Vite2+Vue3 | More challenges in August
  • Actual: Front-end interface request parameter confusion
  • Actual: Implement a Message component with Vue3
  • Actual: Vue3 to implement the Image component, by the way, support lazy loading
  • One Piece, Vue.js 3.0 brings what updates
  • This article digests the major new features of ES7, ES8, and ES9
  • Technical team’s common problems and solutions
  • 10 new features commonly used in ES6
  • Vue3’s Script setup grammar sugar is really cool