在JavaScript中,如何返回一个布尔值,指示一个键是否存在于JSON对象中?

Ale*_*lex 3 javascript json

我有一个相当简单的问题:在Javascript中如何返回布尔值(如果它在JSON中找到)而不是实际值?

例:

 var myJSON = { 
                  "foo" : "bar",
                  "bar" : "foo"
              };
 var keyToLookFor = "foo";
 var found = myJSON[keyToLookFor];

 if (found) {
     // I know I can test if the string exists in the if
 }
  // but is there a way I could just return something like:
 return found;
 // instead of testing found in the if statement and then returning true?
Run Code Online (Sandbox Code Playgroud)

K. *_*ert 8

您必须使用'in'关键字进行检查:

if (keyToLookFor in myJSON) {
}
Run Code Online (Sandbox Code Playgroud)

因此,为了简化它,您可以使用:

return keyToLookFor in myJSON;
Run Code Online (Sandbox Code Playgroud)

  • 或者`if('myjSON中的'foo')`并且如果你想确保`foo`实际上在对象上(而不是在它的原型链中)`myJSON.hasOwnProperty('foo')` (2认同)