Javascript:如何测试响应JSON数组是否为空

时间:2013-05-03 02:18:45

标签: json jquery

我正在取回以下JSON:

{"array":[],"object":null,"bool":false}

我正在测试它,看似详尽无遗,如果声明:

$.ajax({
        type: "GET",
        url: "/ajax/rest/siteService/list",
        dataType: "json",
        success: function (response) {
            var siteArray = response.array;

            // Handle the case where the user may not belong to any groups
            if (siteArray === null || siteArray=== undefined || siteArray=== '' || siteArray.length === 0) {
                            window.alert('hi');
            }
       }
});

但警报没有解雇。 :

2 个答案:

答案 0 :(得分:26)

使用$.isArray()检查对象是否为数组。然后,您可以检查length属性的真实性,看它是否为空。

if( !$.isArray(siteArray) ||  !siteArray.length ) {
    //handler either not an array or empty array
}

答案 1 :(得分:3)

两个空数组彼此不同,因为它们不是同一个对象。

var a = [];
if (a === []){
  // This will never execute
}

使用if (siteArray.length==0)查看数组是否为空,或更简单地if (!siteArray.length)

相关问题