Learn the usage scenarios of ES6 iterator generator, elementary

What is the use of iterator generators? scenes to be used!

Basic knowledge

Today, I learned about es6 generators and iterators. I really have a lot of thoughts. I am a student who is learning the front-end. I may say something is wrong. Please bear with me. It is to summarize what I have learned. Ok now start

Array expansion

Before talking about generator iterators, we must first understand the knowledge of es6, which is the extension of the newly added array of es6. There are three functions: entries(), keys(), values() , these three functions are very similar, they are all in Do one thing, for example:

for(let index of ['a','b','c','d'].keys(){
	console.log(index)  //0,1,2,3
}
for(let values of ['a','b','c'].values()){
	console.log(values)  //'a','b','c'
}
for(let [index,value] of ['a','b','c'].entries()){
	console.log([index,value])  //  [0,'a'],[1,'b'],[2,'c'];
}

The three functions of entries(), keys(), and values() will return a iterator. All the values ​​they return have the function of a iterator, so you can use the for...of method.
Well, if these three methods are understood, then you can enter the generator iterator.

Iterator

What is an iterator? It is a new traversal mechanism. I concluded that it has two cores, one is that it is an interface that can quickly access data. The second one is the pointer used to traverse the data structure. Let me talk about a relatively simple iterator to the array.

const items = ['one','two','three'];
//创建迭代器
const ite = items(Symbol.Iterator)();
//进行获取
console.log(ite.next())   //{value:'one',done:false}
console.log(ite.next())   //{value:'two',done:false}
console.log(ite.next())   //{value:'three',done:false}
console.log(ite.next())   //{value:undefined,done:true}

What does the result of ite.next() mean? It is to traverse the value of the array. Done represents whether the traversal is completed. When ite.next() is called for the fourth time, there is no value, so the value of done is true.

Generator

The generator is a function, but the difference between it and the ordinary function is: the method of declaring the function is:

function* func(ele){
	console.log(ele);
}

Another difference is that yield can only be called inside a function. Explain a yield, that is, the generator suspends the function through the yield keyword, and the explanation is clearer, that is, if you declare a function, you can write a yield inside, and you can "process" the function Stuck there. One method of generator is next(). This method is to reopen the place where the yield is stuck, and let the content in the function continue to go.

function* func(){
	console.log('start');
	yield "2";
	console.log('end');
}
let fn = func();
fn.next(); // "start"  //{value:'2',done:false}

Summarize a little: generator is executed in stages, yield is to suspend execution, and next() is to resume execution.

scenes to be used

There are two types of iterator and generator usage scenarios that are used the most. Let me talk about one type today, and share the other one next time.
This iterator generator is to create an interface for objects that do not have an iterator.
Here is an example:

//第一步 创建一个无迭代器接口的对象
let obj = {
	name: "xiaoChen",
	age: 21
}
//第二步 写一个迭代器接口 (用到了keys(),忘了往上看看哈)
function* objectEntries(obj){
    const Keys = Object.keys(obj);
    for(let key of Keys){
        yield [key,obj[key]];
    }
}
//第三步 给obj接口
obj[Symbol.iterator] = objectEntries;
//第四步 遍历
for(let [name,age] of objectEntries(obj)){
    console.log(`${name}:${age}`); //name: "xiaoChen",age: 21
}
//成功的遍历出obj里面的属性

Well, share it here, and share another scene of use next time.

Guess you like

Origin blog.csdn.net/iloveyu123/article/details/114442791