案例一
var obj = {k1: '111', k2: '2222', k3: '333'};
obj[Symbol.iterator] = function(){
let keys = Object.keys(this);
let len = keys.length;
let idx = -1;
return {
next: function(){
idx++;
return {
value: [idx, keys[idx]],
done: idx>=len
}
}
}
}
for (let [key, val] of obj){
console.log(key, val);
}
案例二(yield)
ar obj = {k1: '111', k2: '2222', k3: '333'};
obj[Symbol.iterator] = function*(){
for(let item of Object.keys(this)) {
yield item;
}
}
for (let [key, val] of obj){
console.log(key, val);
}
Generator 函数里的iterator案例
function* fibs() {
let a = 0;
let b = 1;
while (true) {
yield a;
[a, b] = [b, a + b];
}
}
let [first, second, third, fourth, fifth, sixth] = fibs();