JavaScript递归函数如何获取嵌套数组最后一个元素的索引路径?
递归获取嵌套数组最后一个元素的索引路径实现
最终实现代码
// 示例嵌套数组 let array = [1, [2, 3, [4, 5, ["six", "seven", 6666, [8, 9, [10]]]]]] // 递归查找路径函数 function findLastElementPath(arr, currentPath = []) { // 取当前数组最后一位的索引 const lastIndex = arr.length - 1 const lastElement = arr[lastIndex] // 最后一位是数组则继续递归 if (Array.isArray(lastElement)) { currentPath.push(lastIndex) return findLastElementPath(lastElement, currentPath) } else { // 找到最终非数组元素,拼接路径返回 currentPath.push(lastIndex) return { // 逗号分隔格式:1,2,2,3,2,0 commaPath: currentPath.join(','), // 方括号格式:[1][2][2][3][2][0] bracketPath: currentPath.map(idx => `[${idx}]`).join('') } } } // 调用测试 const pathResult = findLastElementPath(array) console.log(pathResult.commaPath) // 输出 1,2,2,3,2,0 console.log(pathResult.bracketPath) // 输出 [1][2][2][3][2][0] // 验证路径正确性 console.log(eval(`array${pathResult.bracketPath}`)) // 输出10,和数组最后一个元素一致
逻辑说明
- 不需要遍历数组所有元素,每一层直接取最后一位元素判断即可,性能远高于全量遍历
- 用
Array.isArray替代原代码的typeof判断,避免null等特殊值触发类型判断错误 - 通过递归默认参数
currentPath存储索引路径,不需要额外全局变量维护状态 - 直接兼容要求的两种输出格式,可按需取用
内容的提问来源于stack exchange,提问作者user13695929
相关产品推荐
相关产品推荐

