即我该如何表达:
function *(next) {}
Run Code Online (Sandbox Code Playgroud)
带箭头.我已经尝试了所有我能想到的组合,而且我找不到任何关于它的文档.
(目前使用节点v0.11.14)
我正在尝试List使用生成器在ES6中创建一个monad.为了使它工作,我需要创建一个已经消耗了几个状态的迭代器的副本.如何在ES6中克隆迭代器?
function* test() {
yield 1;
yield 2;
yield 3;
}
var x = test();
console.log(x.next().value); // 1
var y = clone(x);
console.log(x.next().value); // 2
console.log(y.next().value); // 2 (sic)
Run Code Online (Sandbox Code Playgroud)
我试着clone和cloneDeep从lodash,但他们是没有用的.以这种方式返回的迭代器是本机函数并在内部保持其状态,因此似乎没有办法用自己的JS代码来完成它.
考虑一下这个python代码
it = iter([1, 2, 3, 4, 5])
for x in it:
print x
if x == 3:
break
print '---'
for x in it:
print x
Run Code Online (Sandbox Code Playgroud)
它会打印1 2 3 --- 4 5,因为迭代器会it记住它在循环中的状态.当我在JS中看似相同的事情时,我得到的只是1 2 3 ---.
function* iter(a) {
yield* a;
}
it = iter([1, 2, 3, 4, 5])
for (let x of it) {
console.log(x)
if (x === 3)
break
}
console.log('---')
for (let x of it) {
console.log(x)
}Run Code Online (Sandbox Code Playgroud)
我错过了什么?