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

递归函数中能否使用push收集嵌套数组目标元素的索引路径?

问题分析

你的代码存在两个核心问题:

  • 每次循环内都重新声明let array = [],各层级的索引存储在独立的空数组中,没有和上层路径拼接,自然无法得到完整的索引链路。
  • 缺少递归终止判断,没有明确定义「最内层元素」的匹配规则,遍历逻辑无法在找到目标时停止并输出结果。
    同时注意判断数组类型时用Array.isArray()比typeof element === "object"更准确,后者会把null、普通对象等也误判为数组类型。
修正后的递归实现

实现1:匹配固定目标值的完整路径

如果你需要精准定位到"you find me"这个元素的完整索引路径,可以用以下代码:

let array = [1, [2, "kkkk", [9, "some", ["six", "seven", 6666, [8, "10", [10,["you find me"]]]]]]];

// 入参依次为:待遍历数组、目标值、当前递归层级的索引路径(默认空数组)
function findIndex(arr, target, currentPath = []) {
    for (let [index, element] of arr.entries()){
        // 拼接当前层级索引,生成新的路径
        const newPath = [...currentPath, index];
        // 匹配到目标值,输出路径并返回
        if(element === target){
            console.log(newPath);
            return newPath;
        }
        // 元素为数组则进入下一层递归
        if(Array.isArray(element)){
            const result = findIndex(element, target, newPath);
            // 找到结果提前终止遍历,不需要继续走剩余分支
            if(result) return result;
        }
    }
}    
findIndex(array, "you find me")

运行后控制台输出[1, 2, 2, 3, 2, 1, 0],就是从最外层数组到目标元素的完整索引路径。

实现2:匹配最内层数组的父级路径

如果你需要的是嵌套最深的子数组的父级路径,也就是你预期的[1,2,2,3,2],可以用以下代码:

let array = [1, [2, "kkkk", [9, "some", ["six", "seven", 6666, [8, "10", [10,["you find me"]]]]]]];

function findIndex(arr, currentPath = []) {
    for (let [index, element] of arr.entries()){
        const newPath = [...currentPath, index];
        if(Array.isArray(element)){
            // 判断当前数组是否还包含嵌套子数组
            const hasChildArray = element.some(item => Array.isArray(item));
            if(!hasChildArray){
                // 找到最内层数组的父级路径,输出并返回
                console.log(currentPath);
                return currentPath;
            }
            findIndex(element, newPath);
        }
    }
}    
findIndex(array)

运行后控制台会输出你预期的[1,2,2,3,2]。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 16:15:03