js判断属性是否存在

常用:

in,hasOwnProperty,比较undefined。

//1、hasOwnProperty()表明它查看对象自身的属性,
      let obj = {
        a:1,
        b:2,
        d:undefined
      }
      console.log(obj.hasOwnProperty('a'))//true
      obj.c = 3
      console.log(obj)//{a: 1, b: 2, c: 3}
      //自己的属性是直接在对象上定义的属性,
      console.log(obj.hasOwnProperty('c'))//true
      console.log(obj.toString)//ƒ toString() { [native code] }
      //而没有检测到继承的属性
      console.log(obj.hasOwnProperty('toString'))//false
    
    //2、 in运算符
    console.log('toString' in obj) //true
    // hasOwnProperty()方法和in操作符之间的主要区别在于后者能检查对象自身和继承的属性
    
    //3、与undefined比较,从对象访问不存在的属性会导致undefined
    console.log(obj.a !== undefined)// true
    console.log(obj.toString !== undefined)//true
    //例外:即使属性name存在(但有undefined值),obj.d !== undefined 判断为false,错误地认为缺少name属性。所以这种方法有误判断的可能。
    console.log(obj.d !== undefined) // false

    //总结,判断属性是否存在,保险起见还是用in,第二种方法

 

posted @ 2022-07-08 13:47  最爱小虾  阅读(1148)  评论(0编辑  收藏  举报