我有一个相当简单的问题:在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)
您必须使用'in'关键字进行检查:
if (keyToLookFor in myJSON) {
}
Run Code Online (Sandbox Code Playgroud)
因此,为了简化它,您可以使用:
return keyToLookFor in myJSON;
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
752 次 |
最近记录: |