let obj = {a:1, b:2, c:3};
// method 1
obj[Symbol.iterator] = function() {
let index = 0,
list = Object.keys(this).map(e=>this[e]);
return {
next: () => {
return {
value: list[index++],
done: index > list.length,
};
},
};
}
// method 2
obj[Symbol.iterator] = function* () {
let list = Object.keys(this).map(e=>this[e]);
for(let v of list) {
yield v;
}
}
for(let item of obj) {
console.log(item); // 1 2 3
}
网友评论