![](/img/trans.png)
[英]How to add if statement in jQuery to check if property exist in JSON file?
[英]jquery check if json var exist
如何使用 jquery 检查 getJSON 后生成的 json 中是否存在键/值?
function myPush(){
$.getJSON("client.php?action=listen",function(d){
d.chat_msg = d.chat_msg.replace(/\\\"/g, "\"");
$('#display').prepend(d.chat_msg+'<br />');
if(d.failed != 'true'){ myPush(); }
});
}
基本上我需要一种方法来查看 d.failed 是否存在,如果它 = 'true' 则不要继续循环推送。
为此,您不需要 jQuery,只需 JavaScript。 您可以通过以下几种方式做到这一点:
typeof d.failed
- 返回类型('undefined'、'Number'等)d.hasOwnProperty('failed')
- 以防它被继承'failed' in d
- 检查它是否被设置(甚至未定义) 您还可以检查 d.failed: if (d.failed)
,但如果 d.failed 未定义、null、false 或零,这将返回 false。 为简单起见,为什么不这样做if (d.failed === 'true')
? 为什么要检查它是否存在? 如果是真的,只需返回或设置某种 boolean。
参考:
http://www.nczonline.net/blog/2010/07/27/determining-if-an-object-property-exists/
昨天发现了这个。 CSS 类似于 JSON 的选择器
您可以将 javascript 成语用于这样的 if 语句:
if (d.failed) {
// code in here will execute if not undefined or null
}
就那么简单。 在您的情况下,它应该是:
if (d.failed && d.failed != 'true') {
myPush();
}
具有讽刺意味的是,正如 OP 在问题中所写的那样,这读作“如果 d.failed 存在并设置为'true'”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.