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

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;
    }
}

排查建议

  1. 打开浏览器控制台的「网络」面板,找到返回myJsonTree的请求,查看实际返回的JSON结构,对比本地测试数据,找出结构不一致的节点
  2. 可以在myFunction开头加入临时调试代码,定位出问题的节点:
function myFunction(node){
    console.log('当前节点:', node); // 打印节点,查看哪个是undefined/null
    if (!node) return;
    // ... 后续代码
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 23:56:00