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

Police.UK API数据循环处理:判断outcome_status是否为null

如何区分outcome_status是null还是包含有效数据?

这是API数据处理里很常见的场景,我给你梳理几个实用的判断方案:

首先,先精准区分null的情况,再验证有效字段的存在和类型:

var outcome = data[i]["outcome_status"];

// 第一步:直接判断是否为null
if (outcome === null) {
  // 处理无结果状态的逻辑
  console.log("这条记录没有结果状态数据");
} else {
  // 第二步:确保outcome是对象类型(防御API返回非预期类型)
  if (typeof outcome === 'object') {
    // 第三步:验证两个字段是否都是字符串类型的有效值
    if (typeof outcome.date === 'string' && typeof outcome.category === 'string') {
      // 这里处理有效数据
      console.log(`结果日期:${outcome.date},类别:${outcome.category}`);
    } else {
      // 处理字段缺失或类型不符的情况
      console.log("结果状态数据格式异常,缺少必要字段或字段类型错误");
    }
  } else {
    // 处理outcome既不是null也不是对象的异常场景
    console.log("结果状态数据类型不符合预期");
  }
}

如果你的项目支持ES2020及以上语法,还可以用可选链操作符(?.)简化代码,但依然要配合类型判断保证严谨性:

var outcome = data[i]["outcome_status"];

if (outcome === null) {
  console.log("无结果状态数据");
} else if (typeof outcome === 'object' && 
           typeof outcome?.date === 'string' && 
           typeof outcome?.category === 'string') {
  // 有效数据处理逻辑
} else {
  console.log("结果状态数据格式异常");
}

额外说明

  • 用outcome === null可以精准区分null,避免和undefined、空对象这类情况混淆;
  • 检查typeof outcome === 'object'是防御性编程,防止API返回字符串、数字等非预期类型导致后续代码报错;
  • 验证字段类型为string,能确保拿到的是符合要求的有效数据,而不是undefined、数字或其他无效值。

内容的提问来源于stack exchange,提问作者Aiden McGree

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 07:50:56