解析JSON报Cannot read property 'url' of undefined 求多场景兼容方案
报错根源
你之前的代码未对floorplan数组下标为1的元素做存在性校验,当数组长度为0或1时,floorplan[1]为undefined,直接访问undefined.url就会触发你遇到的TypeError。
兼容所有场景的解决方案
方案1:可选链+空值合并(最简写法)
适配所有现代运行环境(Chrome 80+、Firefox 72+、Node.js 14+):
var items = JSON.parse(data); return { floorplan1: items.floorplan[0]?.url ?? null, floorplan2: items.floorplan[1]?.url ?? null };
说明:?. 可选链运算符会在左侧值为undefined/null时直接终止属性访问,不会抛出错误;?? 空值合并运算符会将可选链返回的undefined替换为兜底值null,你也可以根据需求替换为空字符串等其他值。
方案2:传统兼容写法
适配所有老旧浏览器、低版本Node.js运行环境:
var items = JSON.parse(data); // 先兜底floorplan为空数组,避免floorplan字段不存在的极端情况报错 var floorplan = items.floorplan || []; return { floorplan1: floorplan[0] ? floorplan[0].url : null, floorplan2: floorplan[1] ? floorplan[1].url : null };
两种方案都可以完美兼容你提到的三种JSON结构:
- 对应JSON A:返回两个floorplan的url值
- 对应JSON B:两个字段都返回null
- 对应JSON C:floorplan1返回对应url,floorplan2返回null
内容的提问来源于stack exchange,提问作者neenkart
相关产品推荐
相关产品推荐

