Home > Web Front-end > JS Tutorial > body text

Understand what a JavaScript iterator is in ten minutes

WBOY
Release: 2021-12-22 18:20:23
forward
3971 people have browsed it

This article brings you relevant knowledge about iterators in JavaScript. Let’s take a look at what an iterator is and how to customize it. I hope it will be helpful to everyone.

Understand what a JavaScript iterator is in ten minutes

1. What is an iterator?

  • Iterator is an interface mechanism that provides a unified access mechanism for various data structures. (That is, to make some data structures that do not support traversal traversable)

The most common is the Array iterator, which returns the values ​​in the array in order.

let arr = [1,2,3,4,5];for (let val of arr) {
    console.log(val);}
Copy after login

Understand what a JavaScript iterator is in ten minutes


2. Custom iterator

So how do we implement iterators?

First of all, it needs to meet two points:

  • Iterable protocol
  • Iterator protocol

Iterable protocol

The iterable protocol allows JavaScript objects to define or customize their iteration behavior

How to satisfy the iterable protocol?

To become an iterable object, an object must implement the @@iterator method.
This means that the object (or an object on its prototype chain) must have a property with the key @@iterator, which can be accessed through the constant Symbol.iterator

That is to say To satisfy the iterable protocol, your object needs to have a property with a key named Symbol.iterator, making it an iterable object.

Iterator protocol

The iterator protocol defines a standard way to produce a sequence of values ​​(whether a finite or infinite number).
When there are a limited number of values, after all values ​​have been iterated, a default return value will be returned.

How to satisfy the iterator protocol?

Your object needs to implement at least one next() method, which returns an iterator object IteratorResult. This iterator object contains two properties done and ·value.

  • done:
    False if the iterator can produce the next value in the sequence.
    True if the iterator has finished iterating the sequence
  • value
    The value returned by the iterator. Done can be omitted when done is true

Then let’s start customizing an iterator

As mentioned above, if you want to customize the iterator Iterator needs to meet the following two conditions:

  • Becomes an iterable object, that is, it has a Symbol.iterator attribute
    (i.e., iterable protocol: Symbol.iterator)
  • The iterator object returns a next() method. This next() method returns an object containing value and done Object of properties
    (i.e. iterator protocol: return { next() { return { value, done } })
let colors = {
    blue : "蓝色",
    green : "绿色",
    yellow : "黄色"}
Copy after login

colors is now a non-iterable object, we want to use for... of traverses it, then you can customize the iterator.
Next, start to implement:

colors[Symbol.iterator] = function() {
	let keys = Object.keys(colors);
	// 如果用 let keys = Reflect.ownKeys(colors),keys 就会包括一些不可枚举的属性
	// 那么后面的 len 要减一,减去Symbol.iterator这个属性
	// 根据实际情况选择使用
	let len = keys.length;
	let index = 0;
	
	return {
	    next : function() {
	        if (index < len) {
	            return {
	                value : colors[keys[index++]],
	                done : false
	            }
	        }
	        return { done : true }
	    }
	}}
Copy after login

Let us verify it:

for (let val of colors) {
    console.log(val);}
Copy after login

Understand what a JavaScript iterator is in ten minutes

[Related recommendations: javascript Study tutorial

The above is the detailed content of Understand what a JavaScript iterator is in ten minutes. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!