php JQuery 和 JSON 数组 - 如何检查数组是否为空或未定义?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13382364/
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
JQuery and JSON array - How to check if array is empty or undefined?
提问by art2
I need to pass php array to jquery for some tasks. The php array is created for SESSION and then json_encoded for jquery. After that I'll store that variable to window js namespace in order to use the array in my jquery script.
对于某些任务,我需要将 php 数组传递给 jquery。php 数组是为 SESSION 创建的,然后为 jquery 进行 json_encoded。之后,我将该变量存储到 window js 命名空间,以便在我的 jquery 脚本中使用该数组。
if(isset($_SESSION['mySession'])){
$json_array = json_encode($php_array);
}
<script>
<?php echo "window.json_from_php = ".$json_array; ?>
</script>
The thing i need to do is to check whether this array exist at all/is empty/undefined before doing anything. The check clause succeeds for 'undefined' operand but not for the rest. How can I check in jquery whether array is empty or not?
我需要做的是在做任何事情之前检查这个数组是否存在/是否为空/未定义。检查子句对“未定义”操作数成功,但对其余操作数无效。如何在 jquery 中检查数组是否为空?
This is the output of the json_encoded array after initialization, when there isn't any elements in the $php_array:
这是初始化后 json_encoded 数组的输出,当 $php_array 中没有任何元素时:
string '[""]' (length=4)
And here is the jquery:
这是jquery:
$(function() {
var results = $('#results');
var js_array = window.json_from_php;
var count = js_array.length;
if ((typeof window.json_from_php === 'undefined') || (js_array === null) || (jQuery.isEmptyObject(js_array)) || (count === 0)) {
$('<p>Array is empty.</p>').appendTo(results);
}
else {
jQuery.each(js_array,function(key,val){
$('<ul><li id="'+key+'">'+val+'</li></ul>').appendTo(results);
});
}
});
回答by JoeFletch
This is how I check for an empty/null json array.
这就是我检查空/空 json 数组的方式。
if (js_array == undefined || js_array == null || js_array.length == 0){
$('<p>Array is empty.</p>').appendTo(results);
}
If your json array is [""]then you may need to add something like
如果您的 json 数组是[""]那么您可能需要添加类似
if (js_array == undefined || js_array == null || js_array.length == 0 || (js_array.length == 1 && js_array[0] == ""))
回答by A. Wolff
This should be enough:
这应该足够了:
if (typeof js_array === 'undefined' || !js_array.length) {
$('<p>Array is empty.</p>').appendTo(results);
} else {...}

