代码之家  ›  专栏  ›  技术社区  ›  Pawan

如何检查JSON中是否存在属性及其值是否为真

  •  0
  • Pawan  · 技术社区  · 6 年前

    我有一个JSON,如下所示

    {
        "name": "mark",
        "age": 35,
        "isActive": true
    }
    

    我需要检查属性IsActive是否存在,它是否也是真的

    我试过这样做,但我想问有没有比下面更好的方法

    var test = {
        "name": "mark",
        "age": 35,
        "isActive": true
    }
    
    if(test.isActive && test.isActive==true)
    {
    alert('yes')
    }
    

    https://jsfiddle.net/o2gxgz9r/54440/

    2 回复  |  直到 6 年前
        1
  •  2
  •   Pranav MS    6 年前

    var test = {
        "name": "mark",
        "age": 35,
        "isActive": true
    }
    
    if(test.hasOwnProperty("isActive") && test.isActive===true){
        alert('yes');
    }else{
       alert("no");
    }
    
        2
  •  2
  •   Barmar 0___________    6 年前

    if (test.isActive === true)
    

    this.isActive undefined true

    ===

    if (test.isActive)