generator函数(含面试题)

generator函数

generator函数是es6提供的一种异步编程解决方案,这个方法比较抽象。
generator函数可以返回多次的函数看看下面这个例子你就很容易明白
如果一个普通函数要返回1-10就只能使用数组或者其他方式存储和generator就可以一次次返回

		function* add() {
			for(let i =0; i<10; i++) {
				yield i;
			}
		} 
		let a = add();
		console.log(a.next()); //{value: 0, done: false}
		console.log(a.next());//{value:1, done: false}
		function add2() {
			let arr =[];
			for(let i =0; i<10; i++) {
				arr.push(i);
			}
			return arr;
		}
		console.log(add2()); //[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

那么前面提到的异步编程是什么意思?
看一下这个例子你就会觉得

		function* hello(){
			console.log("hello开始执行");
			yield ; //暂停
			console.log("hello 执行结束") //执行完返回
			
		}
		let h =  hello();
		
		h.next(); //开始执行
		console.log("外部开始执行");
		h.next();//重新回到hello
		console.log("外部执行结束");

在这里插入图片描述
这个操作有点类似pv操作,也可以理解成可以暂停的函数
在这里插入图片描述
另外还有一个很重要的点generator函数执行结束会返回一个空值
我们就拿上面的例子在来做一点改造

		function* hello(){
			console.log("hello开始执行");
			
			yield 1; //暂停
			console.log("hello 执行结束") //执行完返回
			
			
		}
		let h =  hello();
		console.log(h.next()); //开始执行{value: 1, done: false}
		console.log("外部开始执行");
		console.log(h.next());//重新回到hello{value: undefined, done: true}
		console.log("外部执行结束");

可以看出返回了一个对象value:1是返回的值,并且还有一个done用来判断执行结束了 ,当结束为true还没结束为false
next也可以传参数

		function* add(x){
			var y = yield x +2;
			return  y;
		}
		var g = add(1);
		console.log(g.next()); //{value: 3, done: false}
		console.log(g.next(4));//这里传入的4会作为上一次调用返回的结果 {value: 4, done: true}

谈谈对generator函数的理解

generator是es6提供的一种异步编程解决方案,是可以控制执行的函数,与普通函数相比关键字function与函数名之间多了一个*号,并且可以返回多个值(也是称为状态)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值