Generator 函数

本文详细介绍了Generator函数的特性,包括yield用于定义状态,next()方法的参数传递,return用于结束遍历并返回值,以及try-catch在Generator中的使用。通过实例展示了Generator在控制流上的灵活应用。
摘要由CSDN通过智能技术生成

一,Generator 函数特性

Generator 函数特性,可以通过 yield 关键字,
把函数的执行流挂起,为改变执行流程提供了可能
Generator 有两个区分于普通函数的部分:

1.一是在 function 后面,函数名之前有个 * ;
2.函数内部有 yield 表达式。
3.其中 * 用来表示函数为 Generator 函数,yield 用来定义函数内部的状态。

  1. next()调用
  1. 一般情况下,next 方法不传入参数的时候,yield 表达式的返回值是 undefined 。
  2. 当 next 传入参数的时候,该参数会作为上一步yield的返回值。
  3. done表示函数是否执行完,true执行完,否则false
  4. value获取的是yield后面的值
  1. return 方法

return 方法返回给定值,并结束遍历 Generator 函数。
return 方法提供参数时,返回该参数;不提供参数时,返回 undefined 。

function* func(){
	console.log("one");
	var a = yield 1;
	console.log("two"+a);
	var b = yield 2;
			
	return 99;
	console.log("three"+b);
	yield 3;
	console.log("flor");
	return 4;
}
var f = func();
console.log(f.next());
console.log(f.next(10));
f.return(88);
console.log(f.next(20));
console.log(f.next());
var g = function* () {
	try {
	yield;
	} catch (e) {
	console.log('catch inner', e);
	}
};
var sum = g();
	sum.next();
	console.log(sum.next());
	console.log(sum.next());
	try {
		sum.throw('a');
		sum.throw('b');
	} catch (e) {
	console.log('catch outside', e);
}
function* callee() {
		//     console.log('callee: ' + (yield));
			// yield;
			// console.log('callee: ');
		// }
		// var f = callee();
		// console.log(f.next());
		// console.log(f.next());
		// function* func() {
		//     while (true) {
		//         yield* callee();
		//     }
		// }
		// var f = func();
		// console.log(f.next());
		
		// function* callee() {
		//     console.log('callee: ' + (yield));
		// }
		// var callee = callee();
		// function* func() {
		//     while (true) {
		//         for(var value of callee){
		// 			yield value;
		// 		}
		//     }
		// }
		// var f = func();
		// console.log(f.next());
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值