我如何使用 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')
- 以防它被继承d 中的“失败”
- 检查它是否曾被设置(甚至未定义)
您还可以检查 d.failed:if (d.failed)
,但如果 d.failed 未定义、null、false 或零,这将返回 false。为简单起见,为什么不执行 if (d.failed === 'true')
?为什么要检查它是否存在?如果为真,则返回或设置某种 bool 值。
引用:
http://www.nczonline.net/blog/2010/07/27/determining-if-an-object-property-exists/
关于javascript - jquery 检查 json var 是否存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6105496/