選擇篇(118)-輸出什么?
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
?函數(shù)里執(zhí)行
yield
表達式。通過?
yield*
?關鍵字,我們可以在一個
Generator
?函數(shù)里面執(zhí)行(
yield
表達式)另一個?
Generator
?函數(shù),或可遍歷的對象 (如數(shù)組).
在函數(shù)?
generatorOne
?中,我們通過?
yield
?關鍵字 yield 了一個完整的數(shù)組?
['a', 'b', 'c']
。函數(shù)
one
通過
next
方法返回的對象的
value
?屬性的值 (
one.next().value
) 等價于數(shù)組?
['a', 'b', 'c']
.
console.log(one.next().value) // ['a', 'b', 'c']
console.log(one.next().value) // undefined
在函數(shù)?
generatorTwo
?中,我們使用?
yield*
?關鍵字。就相當于函數(shù)
two
第一個
yield
的值,等價于在迭代器中第一個?
yield
?的值。數(shù)組
['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) // undefined
