javascript - 向数组添加新项目时如何使 symbol.iterator 恢复
问题描述
我通过迭代 Symbol.iterate 对象来打印一个列表。当我向数组添加新项目时,我希望它恢复打印,但它不起作用。我已经尝试了一些方法来做到这一点,但我做不到。我该如何克服这个问题?
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()
推荐阅读
- plot - 如何在 NetLogo 图中输入数字?
- r - 如何在没有 AWS 账户的情况下访问 R 中的公共 AWS S3 对象
- angular - 自定义事件没有被指令捕获
- python - python从其他目录运行文件,缺少图标
- ios - Xcode 11.5 (11E608c) - Swift 5.2.4 非法指令:4
- html - CSS attr() 不适用于 -webkit-line-clamp
- node.js - Instagram 基本显示 API 响应 AccessToken 的 400 错误请求
- c# - 如何处理来自不同操作系统(Linux/Windows)的 SIGTERM
- node.js - 如何设置 ESLint 规则以接受snake_case?
- token - 使用 client_credentials 和 authentication_code grant_type 获取访问令牌时出错