You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何判断数组是否为空?求对应条件判断语句及示例

判断目标数组是否为空(含仅含readTime对象的场景)

看起来你需要判断的是一种特殊的“空数组”——也就是数组里的对象只有readTime字段,而没有document字段的情况,对吧?结合你给出的示例,我整理了几种常用编程语言的实现代码,直接就能用:

JavaScript 实现

核心逻辑:先判断数组本身是否为空,再遍历数组中的每个元素,检查是否所有元素都没有document属性,如果是则判定为“空数组”。

function isEmptyArray(arr) {
  // 先处理数组本身为空的情况
  if (!arr || arr.length === 0) return true;
  // 检查每个元素是否都不包含document字段
  return arr.every(item => !item.document);
}

// 测试你给出的示例
const emptyExample = [ { "readTime": "2019-09-09T15:20:44.648599Z" } ];
const nonEmptyExample = [ 
  { 
    "document": { 
      "name": "projects/warrenty-MdBQxhFSQF11ZKImqL", 
      "fields": { 
        "plate": { "stringValue": "AW69176" },
        "createDate": { "timestampValue": "2019-08-22T21:08:42.563Z" }, 
        "product": { "stringValue": "Paint" }, 
        "exp_date": { "timestampValue": "2026-08-22T21:08:18Z" } 
      }, 
      "createTime": "2019-08-22T21:09:19.972639Z", 
      "updateTime": "2019-09-09T11:33:27.134588Z" 
    }, 
    "readTime": "2019-09-09T15:19:49.433613Z" 
  } 
];

console.log(isEmptyArray(emptyExample)); // 输出 true
console.log(isEmptyArray(nonEmptyExample)); // 输出 false

Python 实现

核心逻辑和JavaScript一致:先判断数组(列表)本身是否为空,再检查所有元素是否都不包含document键。

def is_empty_array(arr):
    # 先处理列表本身为空的情况
    if not arr:
        return True
    # 检查每个元素是否都没有document键
    return all('document' not in item for item in arr)

# 测试示例
empty_example = [ {"readTime": "2019-09-09T15:20:44.648599Z"} ]
non_empty_example = [ 
    { 
        "document": { 
            "name": "projects/warrenty-MdBQxhFSQF11ZKImqL", 
            "fields": { 
                "plate": {"stringValue": "AW69176"},
                "createDate": {"timestampValue": "2019-08-22T21:08:42.563Z"}, 
                "product": {"stringValue": "Paint"}, 
                "exp_date": {"timestampValue": "2026-08-22T21:08:18Z"} 
            }, 
            "createTime": "2019-08-22T21:09:19.972639Z", 
            "updateTime": "2019-09-09T11:33:27.134588Z" 
        }, 
        "readTime": "2019-09-09T15:19:49.433613Z" 
    } 
]

print(is_empty_array(empty_example))  # 输出 True
print(is_empty_array(non_empty_example))  # 输出 False

补充说明

如果你的“空数组”定义只是指数组本身长度为0,那只需要简单判断数组的长度/是否为空即可,比如JavaScript里的arr.length === 0,Python里的not arr。但根据你给出的示例,显然是需要区分仅含readTime的元素和包含业务数据document的元素,所以上面的代码针对的是这个特定场景。

内容的提问来源于stack exchange,提问作者Jonas Bro

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 07:34:05