我从第一眼就知道这听起来像是重复的问题,但我不认为这是...
我正在收到一个 JSON 数组:
var test1 = [] ;
或
var test2 = [{},{},{}] ; //This is empty
我很容易确定 test1
是否为空。
jQuery.isEmptyObject(test1)
我的问题是 test2
...
请注意,在某些情况下,test2 可能会返回如下内容:
var test2 = [{"a":1},{},{}] ; //All these are not empty
var test2 = [{},{"a":1},{}] ; //All these are not empty
var test2 = [{},{},{"a":1}] ; //All these are not empty
以上场景不应算作空。我尝试使用 .length
但它无济于事,因为长度始终为 3...有什么想法吗?
干杯。
最佳答案
function isArrayEmpty(array) {
return array.filter(function(el) {
return !jQuery.isEmptyObject(el);
}).length === 0;
}
通过所有测试。
纯 JavaScript 解决方案是将 !jQuery.isEmptyObject(el)
替换为 Object.keys(el).length !== 0
编辑:使用 Array.prototype.every
function isArrayEmpty(array) {
return array.every(function(el) {
return jQuery.isEmptyObject(el);
});
}
关于javascript - 检查 JSON 数组是否为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18396073/