没有generator之前我们得这样写:(用到闭包)
function next_id(){
var current_id = 0;
return function (){
return ++current_id;
}
}
var g = next_id();
for( let i = 0; i < 10; i++ ){
console.log(g());
}
用generator实现:
function* next_id(){
let current_id =0;
while(true) {
current_id++;
yield current_id;
}
}
let g = next_id();
for( var i = 0; i < 10; i++ ){
console.log( g.next().value )
}
简单大气有没有?
什么是generator,传送门https://blog.csdn.net/zsr1860/article/details/79803038