NodeJS报错:Cannot set properties of undefined (setting 'city')求助
问题分析与解决
核心错误原因
报错TypeError: Cannot set properties of undefined (setting 'city')指向两种明确问题:
result[r]是undefined——你试图给一个不存在的对象赋值属性cty[item.city_id]是undefined——找不到对应city_id的城市数据
具体排查与修复步骤
1. 确认result数组的索引r合法
- 检查
r的取值是否在result数组的有效索引范围内(比如result长度为5,r不能是5或负数) - 确保遍历过程中
r和result的元素是一一对应的,不要用错变量作为索引
2. 提前初始化result[r]对象
如果result是数组,必须先给result[r]创建空对象,再赋值属性:
// 先初始化空对象,避免undefined报错 if (!result[r]) { result[r] = {}; } // 用可选链处理找不到城市的情况 result[r].city = cty[item.city_id]?.name || '未知城市';
3. 校验cty结构与item.city_id的匹配性
- 明确
cty是数组还是对象:如果是数组,item.city_id需为数字索引;如果是对象,item.city_id的类型要和cty的键完全一致(比如cty的键是字符串'101',item.city_id不能是数字101) - 用可选链操作符
?.避免找不到数据时触发报错:
// 即使无匹配城市,也只会返回undefined,不会中断程序 result[r].city = cty[item.city_id]?.name;
4. 精准调试定位
在报错行前添加日志,直接锁定问题点:
console.log('当前索引r:', r); console.log('result[r]是否存在:', !!result[r]); console.log('当前city_id:', item.city_id); console.log('cty中存在该id吗:', !!cty[item.city_id]);
内容的提问来源于stack exchange,提问作者Florian Rahmann
相关产品推荐
相关产品推荐

