js 生成器 Generator 用法随笔

生成器对象是由一个 generator function 返回的,并且它符合可迭代协议和迭代器协议1

Demo 基本用法

function* Father() {
	yield 'a';
	yield 'b';
	yield 'c';
}

var son = Father()
son.next().value // a
son.next().value // b
son.next().value // c
son.next().value // undefined



function*

语法就是有个 * 号, 没什么可以解释




yield

yield 的作用有点像 return
调用 next() 就执行到 yield 并返回它后面的内容
第二次调用 next() 就从上次返回的地方继续执行, 直到下一个 yield
next() 到最后, 没有 yield 了, 就返回 undefined
注:
.next() 返回的是对象
.next().value 才是返回的值




yield*

与 yield 的差别在于多了一个 * 号
yield* 会考虑后面是否可迭代对象, 可迭代就会逐个返回
yield 无论后面是否可迭代, 都完整返回

yield* 还可以用于多层 Generator 的套用

function* generatorOne() {
	yield ['a', 'b', 'c'];
}

function* generatorTwo() {
	yield*['a', 'b', 'c'];
}

const one = generatorOne()
const two = generatorTwo()

console.log(one.next().value) // ["a", "b", "c"]
console.log(one.next().value) // undefined
console.log(two.next().value) // a
console.log(two.next().value) // b
console.log(two.next().value) // c
console.log(two.next().value) // undefined



使用

var son = Father()
son.next()

// Father.prototype === son.__proto__
// true

用法和关系都有点像 var son = new Father()




数据类型

Father 类型是 GeneratorFunction
son 类型是 Generator




方法

Generator.prototype.next()
返回一个由 yield表达式生成的值

Generator.prototype.return()
返回给定的值并结束生成器

Generator.prototype.throw()
向生成器抛出一个错误




Demo 完整代码

<html>

<head>
	<title>js 生成器 Generator 用法笔记</title>
</head>

<body>

	<script type="text/javascript">
		"use strict"

		function* Father() {
			yield 'a';
			yield 'b';
			yield 'c';
		}

		var son = Father()
		var son2 = Father()
		var son3 = Father()

		// Generator.prototype.next()

		console.log(son.next())
		console.log(son.next())
		console.log(son.next())

		// Generator.prototype.return()

		console.log(son2.next())
		console.log(son2.return())
		console.log(son2.return("return")) // 提供了参数, 则参数将被设置为返回对象的value属性的值
		console.log(son2.next())

		// Generator.prototype.throw()

		console.log(son3.next())
		try {
			console.log(son3.throw())
			console.log(son3.throw("throw")) // 提供了参数, 则参数将被设置为返回对象的value属性的值
		} catch (error) {
			console.warn(error)
			console.warn("用于抛出的异常")
		}
		console.log(son3.next())


		function* Father2() {
			let a = yield "a";
			console.log('a:', a);
			let b = yield a + 1;
			yield b + 10;
		}
		const son4 = Father2();

		console.log(son4.next())
		console.log(son4.next(100))
		console.log(son4.next())
		console.log(son4.next())

	</script>
</body>

</html>

end


  1. “符合可迭代协议和迭代器协议” 就意味着可以被 for…of 等迭代 ↩︎

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值