【发布时间】:2020-07-25 23:10:51
【问题描述】:
考虑以下迭代器。它产生字符串 'foo' 和 'bar' 然后返回 'quux' 作为返回值。我可以使用Array.from 从迭代器中提取收益,但如果这样做,我将无法读出返回值。迭代器不再返回返回值,因为 Array.from 已作为协议的一部分接收(并丢弃?)它。
const iterator = (function* () {
yield 'foo'
yield 'bar'
return 'quux'
})()
const [foo, bar] = Array.from(iterator)
const quux = // ???
我能想到的唯一解决方案是编写一个间谍程序来监视迭代并将返回值存储到预定义的变量中,作为Array.from 丢弃返回值之前的副作用。是否有更好的替代方法来访问返回值?
let quux
const spy = function* (i) { /* extract return value from i and store it to quux */ }
const [foo, bar] = Array.from(spy(iterator))
【问题讨论】:
标签: javascript iterator