为何读取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
相关产品推荐
相关产品推荐

