侧边栏壁纸
  • 累计撰写 197 篇文章
  • 累计收到 496 条评论

使用Generator定义Symbol.iterator可迭代对象

2019-11-10 / 0 评论 / 48 阅读
let booksInfo = {
    authDescipt: {
        a: ['hello','book', 'san'],
        b: ['nihao', 'henhao', 'three'],
        c: ['aaa', 'bbb', 'ccc']
    }
}

booksInfo[Symbol.iterator] = function *() {
    let AllAuthDescipt = this.authDescipt;
    let keys = Reflect.ownKeys(AllAuthDescipt)
    let values = []
    while(1) {
        if (!values.length) {
            if (keys.length) {
                values = AllAuthDescipt[keys[0]]
                keys.shift()
                yield values.shift()
            } else {
                return false
            }
        }else {
            yield values.shift()
        }
    }
}
o = []
for (let v of booksInfo) {
    o.push(v)
}

console.log(o)

评论一下?

OωO
取消