es6 中的 generator 生成器


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}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值