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.
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);}
So how do we implement iterators?
First of all, it needs to meet two points:
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.
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
.
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:
Symbol.iterator
attributenext()
method. This next()
method returns an object containing value
and done
Object of properties let colors = { blue : "蓝色", green : "绿色", yellow : "黄色"}
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 } } }}
Let us verify it:
for (let val of colors) { console.log(val);}
[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!