Javascript jquery检查json变量是否存在

Javascript jquery检查json变量是否存在,javascript,jquery,json,push,Javascript,Jquery,Json,Push,如何使用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 != 'tr

如何使用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(); }
    });
}
函数myPush(){
$.getJSON(“client.php?action=listen”,函数(d){
d、 chat\u msg=d.chat\u msg.replace(/\\\\”/g,“\”);
$(“#display”).prepend(d.chat_msg+”
); 如果(d.failed!=“true”){myPush();} }); }

基本上,我需要一种方法来查看d.failed是否存在,如果它为'true',那么就不要继续循环推送。

这不需要jQuery,只需要JavaScript。您可以通过以下几种方式实现:

  • typeof d.failed
    -返回类型(“未定义”、“编号”等)
  • d.hasOwnProperty('failed')
    -以防万一它是继承的
  • d中的“失败”
    -检查是否设置过(甚至未定义)
如果(d.failed),也可以检查d.failed:
,但如果d.failed未定义、为null、为false或为零,则返回false。为了简单起见,如果(d.failed==='true')
,为什么不这样做呢?为什么要检查它是否存在?如果是真的,只需返回或设置某种布尔值

参考:


您可以使用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’”。

昨天发现了这一点。类似CSS的JSON选择器