What is an iterator?An iterator is an interface that provides a unified access mechanism for various data structures. Any data structure can complete the traversal operation as long as the iterator interface is deployed.ES6 created a new traversal command for...of loop, which natively has a data structure with the iterator interface (which can be traversed with for...of). Contains Array, Arguments, Set, Map, String, TypedArray, NodeList. Of course, you can also implement this interface manually, which is convenient for practical use.
Working Mechanism:
- Creates a pointer object pointing to the start of the current data structure.
- The first time the object's next method is called, the pointer automatically points to the first member of the data structure.
- Next, the next method is called continuously, and the pointer moves backward until it points to the last member.
- Each call to the next method returns an object containing the value and done properties.
Preliminary Understanding:
let str=[1,2,3];
console.log(str);
let iterator=str[Symbol.iterator]();
let iteratorValue=str[Symbol.iterator]().next();
console.log(iterator);
console.log(iteratorValue);
The following is to manually implement the iterator, mainly to return an object, and then a pointer field and end mark to move down.
let obj={
id:100,
hobby:["sing", "dance", "rap", "basketball","music~"],
[Symbol.iterator](){
let index=0;
let result={};
return{
next:()=>{
if(index<this.hobby.length){
result={value:this.hobby[index],done:false};
}
else{
result={value:undefined,done:true};
}
index++;
return result;
}
}
}
}
for(let value of obj){
console.log(value);
}
Summarize:
Iterators are an important addition to ES6, providing an interface that can be implemented by any object to continuously return each value of the object being iterated over. Objects implementing the Iterable interface have a Symbol.iterator property that references the default iterator. An object is considered iterable if it has Symbol.iterator on it.
Comments
Post a Comment