JavaScript递归遍历JSON树时访问未定义属性报错排查
问题分析与解决方案
错误根源
报错TypeError: Cannot read properties of undefined (reading 'attribute')的核心原因是:某次递归调用时传入myFunction的node为undefined或null,或者该node本身没有attribute属性。
本地运行正常但部署后报错,大概率是服务器返回的JSON数据结构和本地测试用的不一致,比如:
- 服务器返回的JSON中,某个
children数组里存在null/undefined元素 - 部分节点未携带
children字段(不是空数组,而是完全缺失) - 部分节点缺失
attribute属性 - 根节点
myJsonTree.root本身就是undefined
修复代码
给递归函数加上完整的边界校验,避免访问未定义的属性:
let myJsonTree = ...; // 先校验根节点是否有效 if (myJsonTree?.root) { myFunction(myJsonTree.root); } function myFunction(node){ // 若node为null/undefined,直接终止递归 if (!node) return; // 仅当children是数组时才遍历,避免访问undefined的length属性 if (Array.isArray(node.children)) { for(let i=0; i<node.children.length; i++){ myFunction(node.children[i]); } } // 确认attribute存在后再处理 if ('attribute' in node) { // doing something with node.attribute; } }
排查建议
- 打开浏览器控制台的「网络」面板,找到返回
myJsonTree的请求,查看实际返回的JSON结构,对比本地测试数据,找出结构不一致的节点 - 可以在
myFunction开头加入临时调试代码,定位出问题的节点:
function myFunction(node){ console.log('当前节点:', node); // 打印节点,查看哪个是undefined/null if (!node) return; // ... 后续代码 }
内容的提问来源于stack exchange,提问作者Gio Formichella
相关产品推荐
相关产品推荐

