很多时候,我个人感觉开发过程中一味的使用for in 遍历对象不太方便,使用for of就比较轻松,但是好巧不巧对象没有部署迭代器,这就很烦了。。好在ES6是可以让我们自定义迭代器的,于是我们可以在对象上部署一个迭代器,这个迭代器的功能完全由开发者决定,不一定非要暴力枚举对象上的每个键值对,开发过程中按照实际需求来。
在这里简单实现一个for of枚举对象的值
'use strict'
//迭代器
const obj={
name:"chn",
age:18,
arr:[1,2,3,4],
sex:"男",
[Symbol.iterator](){
let index=0;
const keys=Object.getOwnPropertyNames(this);
return {
next() {
const _this=Object.assign(obj);
return index < _this.arr.length ? { value:_this[keys[index++]],
done: false } : { value: undefined, done: true };
}
}
}
};
for(const value of obj){
console.log(value);
//chn
// 18
// [1, 2, 3, 4]
// 男
}