1function* generatorOne() { 2 yield ['a', 'b', 'c']; 3} 4 5function* generatorTwo() { 6 yield* ['a', 'b', 'c']; 7} 8 9const one = generatorOne() 10const two = generatorTwo() 11 12console.log(one.next().value) 13console.log(two.next().value)
本题为"单选题"
参考答案:
正确选项:C:['a', 'b', 'c'] and a
通过 yield
关键字, 我们在 Generator
函数里执行yield
表达式. 通过 yield*
关键字, 我们可以在一个Generator
函数里面执行(yield
表达式)另一个 Generator
函数, 或可遍历的对象 (如数组).
在函数 generatorOne
中, 我们通过 yield
关键字 yield 了一个完整的数组 ['a', 'b', 'c']
。函数one
通过next
方法返回的对象的value
属性的值 (one.next().value
) 等价于数组 ['a', 'b', 'c']
.
1console.log(one.next().value) // ['a', 'b', 'c'] 2console.log(one.next().value) // undefined
在函数 generatorTwo
中, 我们使用 yield*
关键字。就相当于函数two
第一个yield
的值, 等价于在迭代器中第一个 yield
的值。数组['a', 'b', 'c']
就是这个迭代器. 第一个 yield
的值就是 a
, 所以我们第一次调用 two.next().value
时, 就返回a
。
1console.log(two.next().value) // 'a' 2console.log(two.next().value) // 'b' 3console.log(two.next().value) // 'c' 4console.log(two.next().value) // undefined
最近更新时间:2021-07-03
题库维护不易,您的支持就是我们最大的动力!