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

为何读取null的属性有时返回undefined有时触发TypeError报错?

为什么两个对象解构代码的运行表现存在差异?

核心差异在于解构操作的目标是否是可读取属性的合法对象:

示例1分析

当res为null时,代码里的res || {}会触发逻辑或运算:

  • null在逻辑判断中属于假值,因此res || {}会返回右侧的空对象{}
  • 此时解构操作const { coords } = {}等价于const coords = {}.coords,空对象没有coords属性,所以coords的值为undefined,不会触发报错

对应的代码:

const res = await Geolocation.getGeolocation();
const { coords } = res || {};

示例2分析

当res为null时,直接执行const { points } = res:

  • 对象解构的本质是读取目标的对应属性,等价于const points = res.points
  • null不是对象,无法读取其属性,因此会抛出TypeError: Cannot read properties of null (reading 'points')

对应的代码:

const res = await API.getPoints(
          latitude,
          longitude,
          market,
        );
const { points } = res;

简单总结:示例1通过res || {}给解构操作兜底了一个空对象,避免了读取null属性的错误;示例2没有任何兜底处理,直接读取null的属性导致报错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 22:45:32