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

递归函数中for循环未执行第二次的问题(propa层级)

JavaScript递归函数未触发propa层级二次循环的问题排查

问题概述

运行递归函数时,期望在propa属性对应的数组层级触发第二次for循环,遍历数组内对象的属性,但实际输出仅将整个数组作为单一分支输出,未进入数组元素的属性循环。

错误代码示例

const data = {
  propa: [
    { id: 1, details: { x: 10, y: 20 } },
    { id: 2, details: { x: 30, y: 40 } }
  ]
};

function traverse(obj, path = '') {
  let output = [];
  for (const key in obj) {
    const currentPath = path ? `${path}.${key}` : key;
    if (Array.isArray(obj[key])) {
      // 错误:直接输出整个数组,未遍历数组元素的属性
      output.push(`${currentPath}: ${JSON.stringify(obj[key])}`);
    } else if (typeof obj[key] === 'object' && obj[key] !== null) {
      output = output.concat(traverse(obj[key], currentPath));
    } else {
      output.push(`${currentPath}: ${obj[key]}`);
    }
  }
  return output;
}

console.log(traverse(data));

当前错误输出

["propa: [{"id":1,"details":{"x":10,"y":20}},{"id":2,"details":{"x":30,"y":40}}]"]

问题原因

代码在处理数组类型的propa属性时,仅将整个数组序列化为字符串后直接添加到输出结果,没有对数组中的每个对象元素调用递归函数,因此无法触发数组元素层级的for循环,也就无法遍历元素内部的id、details等属性。

修复方案

当检测到当前值为数组时,遍历数组的每个元素,为每个元素生成对应的路径(可添加索引标识),并对元素执行递归遍历,将结果合并到输出数组中:

const data = {
  propa: [
    { id: 1, details: { x: 10, y: 20 } },
    { id: 2, details: { x: 30, y: 40 } }
  ]
};

function traverse(obj, path = '') {
  let output = [];
  for (const key in obj) {
    const currentPath = path ? `${path}.${key}` : key;
    if (Array.isArray(obj[key])) {
      // 遍历数组每个元素,递归处理元素内部属性
      obj[key].forEach((item, index) => {
        const itemPath = `${currentPath}[${index}]`;
        output = output.concat(traverse(item, itemPath));
      });
    } else if (typeof obj[key] === 'object' && obj[key] !== null) {
      output = output.concat(traverse(obj[key], currentPath));
    } else {
      output.push(`${currentPath}: ${obj[key]}`);
    }
  }
  return output;
}

console.log(traverse(data));

修复后输出

[
  "propa[0].id: 1",
  "propa[0].details.x: 10",
  "propa[0].details.y: 20",
  "propa[1].id: 2",
  "propa[1].details.x: 30",
  "propa[1].details.y: 40"
]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 18:35:28