var people={
name:'test',
sex:'male',
hobbies:['ball','paint','sing'],
[Symbol.iterator](){
const _this=this;
const keys = Reflect.ownKeys(_this) // 获取到对象的key值列表
let index=0;
return {
next(){
if(index<keys.length - 1){
return {
value: _this[keys[index++]], // 想返回什么 就返回什么 keys[index++]
done:false
}
}
return {
value:keys[index++],
done:true
}
}
}
}
};
for(let h of people){
console.log(h)
}
// test
// male
// ["ball", "paint", "sing"]
Symbol.iterator实现for of遍历对象
最新推荐文章于 2026-05-18 05:06:44 发布
该博客介绍了如何创建一个具有Symbol.iterator属性的对象,通过这个属性实现对对象属性的迭代遍历。内容涉及到Reflect.ownKeys方法用于获取对象的所有键,以及如何在迭代器中控制遍历流程。

873

被折叠的 条评论
为什么被折叠?



