如何制作符号.当向数组中添加新项时,迭代器恢复



我通过迭代Symbol来打印一个列表。遍历对象。当我向数组中添加新项时,我想让它恢复打印,但它不工作。我试过一些方法,但我做不到。我怎样才能克服这个问题呢?

let arr = [{
name : "Computer",
sold : 1000
},
{
name: "Printer",
sold: 250
},
{
name: "Camera",
sold:290
},
{
name: "Gamepad",
sold: 800
},
{
name: "Keyboard",
sold: 2100
}
]
const iteratorArr = arr[Symbol.iterator]();
const listAll = () => {
var it = iteratorArr.next()
while(!it.done) {
console.log(it.value) 
it = iteratorArr.next()
}
}
listAll()
arr.push({name:"Mouse",sold: 2900})
listAll()

数组迭代器(实际上,任何内置迭代器)在耗尽一次后不支持恢复。可以在将值添加到数组之前创建迭代器,然后仍然迭代它们,但在此期间不能运行迭代器直至完成。例子:

const arr = ['a', 'b'];
const iter = arr.values();
console.log(iter.next().value); // not yet done
console.log(iter.next().value); // not yet done
arr.push('c');
console.log(iter.next().value); // not yet done
console.log(iter.next().done); // no value left, closing
arr.push('d');
console.log(iter.next().done); // still closed

要得到你想要的行为,你需要实现你自己的迭代器:

let arr = [
{ name : "Computer", sold : 1000 },
{ name: "Printer", sold: 250 },
{ name: "Camera", sold:290 },
{ name: "Gamepad", sold: 800 },
{ name: "Keyboard", sold: 2100 }
]
const iteratorArr = {
index: 0,
next() {
const done = this.index >= arr.length
return {done, value: done ? undefined : arr[this.index++]}
},
[Symbol.iterator]() { return this }
}
const listRemaining = () => {
for (const value of iteratorArr) {
console.log(value)
}
console.log(iteratorArr);
}
listRemaining()
arr.push({name:"Mouse",sold: 2900})
listRemaining()

相关内容

  • 没有找到相关文章

最新更新