15

I'm getting back the following JSON:

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

And I'm testing it with the following, seemingly exhaustive, if statement:

$.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');
            }
       }
});

But the alert is not firing. :[

4

2 回答 2

28

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

if( !$.isArray(siteArray) ||  !siteArray.length ) {
    //handler either not an array or empty array
}
于 2013-05-03T02:33:38.590 回答
6

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

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

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

于 2013-05-03T02:27:02.377 回答