夜间模式CodeSnippetStyle:
日间模式CodeSnippetStyle:

0%


#######对象迭代器######

对象迭代器接口

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);
}
posted @ 2021-04-12 21:59  暮冬有八  阅读(305)  评论(0编辑  收藏  举报
BACK TO TOP

😀迷海无灯听船行。Github WeChat