获取对象key集合的一些姿势

有原始对象:

const obj = {
    a: 1,
    [Symbol('b')]: 2
}

再加工一下:

Object.defineProperty(obj,'c',{
    value: 3,
    enumerable: false
})

Object.prototype.d = 4

姿势1

const keys = []
for (let key in obj){
    keys.push(key)
}
console.log(keys) // ["a", "d", "e"]

key特点:自身及原型链上可枚举、非Symbol的key

姿势2

console.log(Object.keys(obj))  // ["a"]

key特点:自身可枚举、非Symbol 的key

姿势3

console.log(Object.getOwnPropertyNames(obj)) // ["a", "c"]

key特点:自身非Symbol的key

姿势4

console.log(Object.getOwnPropertySymbols(obj)) // [Symbol(b)]

key特点:自身的Symbol key

姿势5

console.log(Reflect.ownKeys(obj)) // ["a", "c", Symbol(b)]

key特点:姿势4 + 姿势5