// 获取可枚举的自身属性
function fn1(obj){
return Object.keys(obj)
}
// 获取自身属性
function fn2(obj){
return Object.getOwnPropertyNames(obj)
}
// 获取可枚举的自身和继承属性
function fn3(obj){
const res=[]
for(const k in obj){
res.push(k)
}
return res
}
// 获取所有属性
function fn4(obj){
let res=[]
do{
res=res.concat(Object.getOwnPropertyNames(obj))
}while(obj=Object.getPrototypeOf(obj))
return res
}
Object.prototype.a=1
const obj=Object.create({b:2})
obj.c=3
obj.d=4
Object.defineProperty(obj,'d',{
enumerable:false
})
console.log(fn1(obj)); // [ 'c' ]
console.log(fn2(obj)); // [ 'c', 'd' ]
console.log(fn3(obj)); // [ 'c', 'b', 'a' ]
console.log(fn4(obj)); // [ 'c', 'd', 'b', 'a', 'constructor', '__defineGetter__', ... ]
标签:function,遍历,obj,res,Object,js,return,console,属性
From: https://www.cnblogs.com/ruchoc/p/16753803.html