zoukankan      html  css  js  c++  java
  • 【js】--------------判断一个对象是否有某个属性-------------【劉】

    js检测对象中是否存在某个属性

      使用in关键字

    • var obj = {x:1}
      "x" in obj    //true 自身属性
      "j" in obj    //false 自身没有原型也没有
      "toString" in obj    //true  原型上的属性

      如果是原型链上的属性,判断也为true

      使用hasOwnProperty

    var obj = {x:1}
    obj.hasOwnProerty("x")    //true   自身属性
    obj.hasOwnProerty("y")    //false  自身没有原型也没有
    obj.hasOwnProperty("toString")    //false  原型上的属性

      使用undefined判断

    var o={x:1};
    o.x!==undefined;        //true
    o.y!==undefined;        //false
    o.toString!==undefined  //true

    该方法存在一个问题,如果属性的值就是undefined的话,该方法不能返回想要的结果,如下。

    var o={x:undefined};
    o.x!==undefined;        //false,属性存在,但值是undefined
    o.y!==undefined;        //false
    o.toString!==undefined  //true

      

  • 相关阅读:
    web.xml
    web.xml hello1代码分析
    annotation
    injection
    container
    build tool
    version control
    url与uri的区别
    函数式语言
    http协议解析过程
  • 原文地址:https://www.cnblogs.com/lstcon/p/10345371.html
Copyright © 2011-2022 走看看