ECMAScript 2015 迭代器协议:实现自定义迭代器
迭代器协议定义了一种标准的方式来产生一个有限或无限序列的值,并且当所有的值都已经被迭代后,就会有一个默认的返回值。
当一个对象只有满足下述条件才会被认为是一个迭代器:它实现了一个 next()
的方法并且拥有特殊含义。
let fridge = { name: "卡萨帝冰箱", color: "白色", brand: "海尔" }; fridge[Symbol.iterator] = () => { let keys = Object.keys(fridge); return { next: () => { let attr = keys.shift(); return { done: attr == null, value: fridge[attr] }; } }; }; for (let attr of fridge) { console.log(attr); } let desc = [...fridge]; console.log(desc);
一个良好的迭代即实现了迭代器协议,又实现了可迭代协议,方式就是可迭代协议返回的是自身。
生成器对象 既是迭代器也是可迭代对象。
let fridge = { name: "卡萨帝冰箱", color: "白色", brand: "海尔" }; let keys = Object.keys(fridge); let fridgeIterator = { next: () => { let attr = keys.shift(); return { done: attr == null, value: fridge[attr] }; }, [Symbol.iterator]:()=>fridgeIterator }; for (let attr of fridgeIterator) { console.log(attr); } keys = Object.keys(fridge); let desc = [...fridgeIterator]; console.log(desc);