zl程序教程

您现在的位置是:首页 >  前端

当前栏目

[Javascript] Yield an Array, String, or Any Iterable from a Generator (yield*)

JavaScript string or from Array an any Generator
2023-09-14 08:59:14 时间

Generators allow you to use the yield * syntax to yield each iteration of nested iterable as part of the main iterations. This enables you to combine multiple arrays, strings, or any iterable with anything you want to yield from your main generator.

 

const abcs = ["A", "B", "C"]

const reverseIterator = function* (array) {
    yield* array
    yield* array.map(letter => letter.toLowerCase())
    yield Math.random()
    yield* "wan"
}

const iterator = reverseIterator(abcs)

for (let value of iterator) {
    console.log(value)
}


/*
A
B
C
a
b
c
0.1234
w
a
n
*/