枚举属性
- 有时候需要遍历或获取对象的所有属性。
- Enumerable 枚举
let o = { x: 1, y: 2, z: 3 }
// 对象继承内置的方法,是不可枚举的
console.log(o.propertyIsEnumerable('toString'))
// 自己添加的属性,默认是可枚举的
console.log(o.propertyIsEnumerable('x'))
for (let p in o) {
console.log(p) // =>x,y,z,但没有toString
}
// 跳过继承属性
for (let p in o) {
if (!o.hasOwnProperty(p)) continue
}
// 跳过所有方法
for (let p in o) {
if (typeof o[p] === 'function') continue
}