Learn the iterator of javascript
- 2021-11-13 06:29:25
- OfStack
What does an iterator look like in js
Iterative protocol
Iterable protocol
Iterator protocol
Iterative process
Iterative summary
Custom iteration
Traditional writing
Generator function writing
Brief introduction
Iterator is a design pattern that can be traversed on container objects such as linked lists and arrays without concern for the implementation details of memory allocation of container objects. The simple understanding is that you can get the data one by one, similar to a moving pointer, but it will tell us when it will end. In this way, we can get the data and do something we need to do.
What does an iterator look like in js
In javascript, the iterator is a special object that has an next () method that returns one object (the result object) each time it is called. The resulting object has two attributes: one is value, which represents the next value to be returned; The other is done, which is a Boolean value and true if it has iterated to the last value in the sequence. The iterator also holds an internal pointer to the position of the value in the current collection, and every time the next () method is called, it returns the next available value, similar to the structure of the following object.
{
next: function () {
return {
value:'',
done: true / false
}
}
}
Iterative protocol
With the ability of javascript language further improved, a new data type such as Map, Set, WeakMap, etc., for these different data structures, the iteration of 1 can be unified, and es6 adds an iteration protocol.
Iterative protocol is not a new built-in implementation or syntax, but a protocol. These protocols can be implemented by any object that follows certain conventions.
Iterative protocol is divided into two protocols: iterative protocol and iterator protocol.
The simple understanding is that any object in js can be traversed as long as it meets the iterative protocol
Iterable protocol
To be an iterable object, an object must implement the @ @ iterator method. This means that the object (or an object in its prototype chain) must have a property with the key @ @ iterator, which can be accessed through the constant Symbol. iterator:
Simply understand, if you want a thing to traverse, then this thing should have a @ @ iterator, which can be accessed through Symbol. iterator
属性 |
值 |
[Symbol.iterator] |
1个无参数的函数,其返回值为1个符合迭代器协议的对象。 |
Iterator protocol
The iterator protocol defines a standard way to generate 1 series of values, whether finite or infinite. When the number of values is limited and all values are iterated, a default return value is returned.
An object complies with the iterator protocol only if an next () method with the following semantics (semantic) is implemented:
属性 |
值 |
next |
1个无参数函数,返回1个应当拥有以下两个属性的对象: done(boolean) next() 方法必须返回1个对象,该对象应当有两个属性: done 和 value,如果返回了1个非对象值(比如 false 或 undefined),则会抛出1个 异常("iterator.next() returned a non-object value")。 |
Iterative process
When an object needs to be iterated (for example, when written to an for... of loop), first, its @ @ iterator method is called without parameters (this returns {next: function () {}}), and then the iterator returned by this method is used to get the value to be iterated (in fact, this next () method is constantly called)
Iterative summary
Iterative protocol can be summed up as, if one thing is to be traversed, it must satisfy iterative protocol and iterator protocol
Iterable protocol: This object must have @ @ iterator, which can be accessed through Symbol. iterator Iterator protocol: Is an object, the next () function of this object returns an object, this object includes two attributes, one is value, one is done (boolean, whether it is the last element, value can be omitted when done is true)That is to say, the iterator object is essentially a pointer object. Used to move the pointer through next () of the pointer object.
Custom iteration
Object is not implemented iterator, so can not traverse the object, in order to achieve the object traversal, we need to achieve the above-mentioned iterator on the object, usually there are two ways to write, one is the traditional way of writing, this need to control their own internal state, the other one is to use the generator function returned by the Generator iterator to achieve, the code is as follows:
Traditional writing
let obj = {
name: 'joel',
adress: 'gz',
[Symbol.iterator]: () => {
// Don't use it here this , Because it is return fn, this Will be lost
let index = -1, atrrList = Object.keys(obj);
const objIterator = {
next: () => {
let result = ''
index++
if (index < atrrList.length) {
result = {
value: atrrList[index],
done: false
}
} else {
result = {
done: true
}
}
return result
}
}
return objIterator
}
}
for (const item of obj) {
console.log('atrrs:' + item + ',value:' + obj[item])
}
Generator function writing
// Add iterators to non-iterative objects
let obj = {
a: 1,
b: 2
}
obj[Symbol.iterator] = function* () {
let keys = Object.keys(obj);
// Get key The length of the value
let len = keys.length;
// Define loop variables
let n = 0;
// Conditional judgment
while (n <= len - 1) {
yield { k: keys[n], v: obj[keys[n]] };
n++
}
}
// Returns an object's key And value
for (let { k, v } of obj) {
console.log(k, v);
}
For other information, such as built-in iterative objects, syntax for iterative objects, built-in api that accepts iterative objects, etc., please click here