#######对象迭代器######
对象迭代器接口
let obj = {
key1: "val1",
key2: "val2",
key3: "val3",
};
function cusObjIterator(obj) {
let metaItemArr = [];
for (let i in obj) {
let metaItem = [];
metaItem[0] = i;
metaItem[1] = obj[i];
metaItemArr.push(metaItem);
}
let index = 0;
return {
next() {
if (index < metaItemArr.length) {
return { value: metaItemArr[index++], done: false };
} else {
return { value: undefined, done: true };
}
},
};
}
let iterObj = cusObjIterator(obj);
console.log(iterObj.next());
console.log(iterObj.next());
console.log(iterObj.next());
console.log(iterObj.next());
使用生成器生成对象迭代器
let obj = {
key1: 'val1',
key2: 'val2',
key3: 'val3'
}
function* cusGenerator(obj) {
for (let i in obj) {
yield [i, obj[i]]
}
}
let cusGener = cusGenerator(obj);
console.log(cusGener);
for (let i of cusGener) {
console.log(i);
}