const musicCollection = {
albums: [{
title: "Amends",
artist: "Grey Daze",
year: "2020"
},
{
title: "Here on Earth",
artist: "Tim McGraw",
year: "2020"
},
{
title: "Orquídeas",
artist: "Karly Loaiza",
year: "2024"
}
]
}
musicCollection[Symbol.iterator] = function() {
return {
current: 0,
to: this.albums.length,
next() {
return this.current < this.to ? {
done: false,
value: musicCollection[this.current++]
} : {
done: true
};
}
}
}
for (let album of musicCollection) {
console.log(`${album.title} - ${album.artist} (${album.year})`);
}
musicCollection排队这是一个对象,它没有整数字段,但有一个字段
albums包含它们。因此,要修复它,只需将上面的行替换为以下行
在某些情况下使用迭代器更容易使用生成器函数
由于在这种情况下迭代器功能与已知的数组迭代器一致,因此您可以直接使用它: