对象属性获取关于Object.keys,hasOwnProperty等几种方法

67 阅读1分钟
const symbol = Symbol("descript")
const obj = Object.create({ parent: 'parent' })
Object.assign(obj, {
    name: "demo",
    age: 18,
    [symbol]: 'symbol',
    iUnder:undefined,
    iNull:null,
})
Object.defineProperty(obj, "name", {
    enumerable: false
})

//obj[key] 包含不可枚举以及原型上的属性
obj["name"] => "demo"
obj["age"] => 18
obj[symbol] => 'symbol'
obj["iUnder"] => undefined
obj["iNull"] => null
obj["parent"] => parent


//JSON.stringify(obj) 返回自身属性且不包含不可枚举和Symbol以及值为undefined的值
{"age":18,"iNull":null}


//Object.keys(obj) 返回自身属性且不包含不可枚举和Symbol的值
[ 'age', 'iUnder', 'iNull' ]

//obj.hasOwnProperty(key) 返回自身所有属性包含不可枚举以及Symbol
obj.hasOwnProperty("name") //true
obj.hasOwnProperty("age") //true
obj.hasOwnProperty(symbol) //true
obj.hasOwnProperty("iUnder") //true
obj.hasOwnProperty("iNull") //true
obj.hasOwnProperty("parent") //false


// key in obj 返回自身所有以及原型链上的属性 包含不可枚举和Symbol
"name" in obj //true
"age" in obj //true
symbol in obj //true
"iUnder" in obj //true
"iNull" in obj //true
"parent" in obj //true