首页 > 解决方案 > 向数组添加新项目时如何使 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()

标签: javascriptiterator

解决方案


数组迭代器(实际上,任何内置迭代器)在用完一次后不支持恢复。可以在向数组添加值之前创建迭代器,然后仍然对其进行迭代,但您不得在其间运行迭代器以完成。例子:

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()


推荐阅读