js 对象实现for of 遍历 (defineProperty自定义功能)

1.对象
let myObject = {
a: 2,
b: 3
}
2.定制遍历规则
Object.defineProperty(myObject, Symbol.iterator, {
enumerable: false,
writable: false,
configurable: true,
value: function () {
let o = this
let idx = 0
let ks = Object.keys(o)
return {
next: function () {
return {
value: o[ks[idx++]],
done: (idx > ks.length)
}
}
}
}
})

3.遍历对象
for (let obj of myObject) {
console.log(obj)
}
posted @ 2020-08-07 15:59  Leduo  阅读(2056)  评论(0编辑  收藏  举报