一
generator:生成器
generator函数的特征是function关键字和函数名之间有*,函数内部有yield表达式如下:
function* helloWorldGenerator() {
var a = 'hello';
yield a;
// yield 'hello';
var b = 'world';
yield b;
yield 'ending';
return null;
}
// generator方法调用后会返回一个遍历器对象,该对象可以使用next或for...of遍历
var hel = new helloWorldGenerator();
//next 遍历
console.log(hel.next());//{value:hello,done:false}
console.log(hel.next());//{value:world,done:false}
console.log(hel.next());//{value:endeing,done:false}
console.log(hel.next());//{value:null,done:true}
// for of 遍历
for(it of hel){
console.log(it);// hello world ending null
}
注意:若在helloWorldGenerator函数中最后没有return时,这时他会自动返回一个undefined
二
generator函数内部没有yield表达式的时候,此时调用f()内部的代码也不会执行,除非执行了next,例如:
function* f() {
console.log('执行了!');// 执行两秒后输出。并且要是没有setTimeout执行了next 则不会打印输出结果。
}
var generator = f();
setTimeout(function() {
generator.next();
}, 2000);
var myIterable = {};
myIterable[Symbol.iterator] = function*() {
yield 1;
yield 2;
yield 3;
};
console.log([...myIterable]); // [1, 2, 3] 如果不是yield 而是return的话 则不会被放进数组内
function* f() {
var a = yield 'hello';
yield a;
}
var generator = f();
console.log(generator.next());//{value:hello,done:false}
console.log(generator.next('world'));//{value:wold,done:false}