检测js对象属性是否存在的几种方法


开发过程中经常需要检测某个属性是否存在,下面对常用的检测方法进行整理

使用in检测

直接看代码

let demo = {
    age: 18
}

console.log("age" in demo)      // true

但是该方法同样会对原型链上的属性进行检测,测试代码如下。

let demo = {
    
}
demo.__proto__.age = 18

console.log("age" in demo)      //true

该方法的注意事项如下

  • 必须使用字符串的形式检测属性,如”age”
  • 若原型链上存在属性会产生干扰

使用hasOwnProperty

let demo = {
    age: 18
}
demo.__proto__.name = "maple"

console.log(Object.hasOwnProperty.call(demo, "age"))    // true
console.log(Object.hasOwnProperty.call(demo, "name"))   //false
  • 该方法只会检测对象自身的属性,但是应确保对象继承自Object(如果使null或undefined会报错,可以使用call/apply进行绑定)

使用propertyIsEnumerable

let demo = {
    age: 18
}
Object.defineProperty(demo, "sex",{
    value: "F",
    enumerable: false,
    configurable: true,
    writable: true
})
demo.__proto__.name = "maple"

console.log(Object.propertyIsEnumerable.call(demo, "age"))    // true
console.log(Object.propertyIsEnumerable.call(demo, "name"))   //false
console.log(Object.propertyIsEnumerable.call(demo, "sex"))  //false
  • 相对于Object.hasOwnProperty,该方法还会检测对象的enumerable属性。

Author: Maple
Reprint policy: All articles in this blog are used except for special statements CC BY 4.0 reprint polocy. If reproduced, please indicate source Maple !
  TOC