方法一
function it(){
let keys = Object.keys(this)
let obj = this
let idx = 0
let length = keys.length
return {
next: function() {
if (idx < length) {
let ret = {
value: {
key: keys[idx],
val: obj[keys[idx]]
},
done: false
}
idx ++
return ret
} else {
return {
value: undefined,
done: true
}
}
}
}
}
var a = {x:1, y:2, z:3}
a[Symbol.iterator] = it
for (let v of a)
{
console.log('------------')
console.log(v)
}
/*
------------
{ key: 'x', val: 1 }
------------
{ key: 'y', val: 2 }
------------
{ key: 'z', val: 3 }
*/
for,of循环会在迭代器返回对象的done属性为true时,停止循环,且不执行当前循环体。
方法二
function* it(obj) {
let propKeys = Object.keys(obj);
// console.log(propKeys) // [ 'x', 'y', 'z' ]
for (let propKey of propKeys) {
yield {
key: propKey,
val: obj[propKey]
}
}
}
var a = {x:1, y:2, z:3}
for (let v of it(a))
{
console.log('------------')
console.log(v)
}
方法三
function* it(obj) {
let propKeys = Object.keys(this);
for (let propKey of propKeys) {
yield {
key: propKey,
val: this[propKey]
}
}
}
var a = {x:1, y:2, z:3}
a[Symbol.iterator] = it
for (let v of a)
{
console.log('------------')
console.log(v)
}