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

如何修复读取null属性的TypeError,筛选法国山脉数据?

问题排查与解决:筛选法国山脉时的空值访问错误

问题描述

我有一份全球山脉列表,需筛选出所有法国山脉,判断依据是iso3166_1Alpha2属性值为FR。但部分山脉无该属性值,脚本遇到null值时抛出错误:Uncaught (in promise) TypeError: Cannot read properties of null (reading 'iso3166_1Alpha2')。我的!== null检查逻辑无效,附上代码请求排查原因并解决。

原代码

function addJSON() {
  let url = "https://development.example.com/admin/mtn/json/mtn_areas.geojson";
  fetch(url)
    .then(function (response) {
      return response.json();
    })
    .then(function (data) {
      let mtn = data.features;
      for (var i = 0; i < mtn.length; i++) {
        if (mtn[i].properties.location.iso3166_1Alpha2 !== null) {
          x = mtn[i].properties.location.iso3166_1Alpha2;
          console.log(x);
        }
      }
    });
}

错误原因

你的检查逻辑只针对iso3166_1Alpha2是否为null,但忽略了**mtn[i].properties.location本身可能是null或undefined**。当location为null时,直接访问它的子属性iso3166_1Alpha2会触发类型错误,这就是你的检查无效的核心原因。

解决方案

方案1:逐层空值校验(兼容性强)

先确认location存在,再检查目标属性值,避免空值访问:

function addJSON() {
  let url = "https://development.example.com/admin/mtn/json/mtn_areas.geojson";
  fetch(url)
    .then(function (response) {
      return response.json();
    })
    .then(function (data) {
      let mtn = data.features;
      for (var i = 0; i < mtn.length; i++) {
        const location = mtn[i].properties.location;
        // 先判断location不为空,再校验法国的国家码
        if (location && location.iso3166_1Alpha2 === 'FR') {
          console.log(location.iso3166_1Alpha2);
        }
      }
    });
}

方案2:使用可选链操作符(ES2020+,代码更简洁)

通过?.操作符自动跳过空值的属性访问,简化代码:

function addJSON() {
  let url = "https://development.example.com/admin/mtn/json/mtn_areas.geojson";
  fetch(url)
    .then(function (response) {
      return response.json();
    })
    .then(function (data) {
      let mtn = data.features;
      for (var i = 0; i < mtn.length; i++) {
        // 若location为空,countryCode会直接变为undefined,不会报错
        const countryCode = mtn[i].properties.location?.iso3166_1Alpha2;
        if (countryCode === 'FR') {
          console.log(countryCode);
        }
      }
    });
}

补充说明

  • 方案1适用于所有浏览器环境,兼容性拉满;
  • 方案2需要运行环境支持ES2020或更高版本(现代浏览器、配置Babel的项目均可使用)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 12:39:52