web-interview
web-interview copied to clipboard
[选择题] 52.(单选题)下面代码的输出是什么
function* generatorOne() {
yield ['a', 'b', 'c'];
}
function* generatorTwo() {
yield* ['a', 'b', 'c'];
}
const one = generatorOne()
const two = generatorTwo()
console.log(one.next().value)
console.log(two.next().value)
A:a and a
B: a and undefined
C: ['a', 'b', 'c'] and a
D: a and ['a', 'b', 'c']
答案:C
解析:
通过yield关键字,我们在Generator函数里执行yield表达式.通过yield*关键字,我们可以在一个Generator函数里面执行(yield表达式)另一个Generator 函数,或可遍历的对象(如数组).
在函数generatorOne中,我们通过yield关键字yield 了一个完整的数组['a', 'b', 'c']。函数one通过next方法返回的对象的value属性的值(one.next().value)等价于数组['a', 'b', 'c']
console.log(one.next().value) // ['a', 'b', 'c']
console.log(one.next().value) // undefined
在函数generatorTwo中,我们使用yield*关键字。就相当于函数two第一个yield的值,等价于在迭代器中第一个yield的值。数组 ['a', 'b', 'c'] 就是个迭代器.第一个 yield的值就是a ,所以我们第_次调用two.next().value 时,就返回 a。
console.log(two.next().value) // 'a'
console.log(two.next().value) // 'b'
console.log(two.next().value) // 'c'
console.log(two.next().value) // underfined