jQuery Javascript:如何测试响应 JSON 数组是否为空
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16350604/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript: How to test if response JSON array is empty
提问by Lurk21
I'm getting back the following JSON:
我取回以下 JSON:
{"array":[],"object":null,"bool":false}
And I'm testing it with the following, seemingly exhaustive, if statement:
我正在使用以下看似详尽的 if 语句对其进行测试:
$.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. :[
但是警报没有触发。:[
回答by Arun P Johny
Use $.isArray()to check whether an object is an array. Then you can check the truthness of the length
property to see whether it is empty.
使用$.isArray()检查对象是否为数组。然后你可以检查length
属性的真实性,看它是否为空。
if( !$.isArray(siteArray) || !siteArray.length ) {
//handler either not an array or empty array
}
回答by Phrogz
Two empty arrays are not the same as one another, for they are not the same object.
两个空数组彼此不同,因为它们不是同一个对象。
var a = [];
if (a === []){
// This will never execute
}
Use if (siteArray.length==0)
to see if an array is empty, or more simply if (!siteArray.length)
使用if (siteArray.length==0)
看看如果数组是空的,或者更简单if (!siteArray.length)