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

如何遍历嵌套数组返回包含指定文件名的完整文件路径

实现方案
  • 不要仅单独存储文件名列表,提前做一次全量遍历构建「文件名-对应完整路径数组」的映射表,预处理仅执行1次,后续所有查询都是O(1)时间复杂度,远高于每次查询都遍历全数组的方案,完美适配大型数组场景
  • 映射表的值用数组存储,天然适配同文件名对应多条不同数字标识路径的需求

完整实现代码如下:

const c = [
  [
    ['dd\\32323232323:this1', 'dd\\43564564:this2'],
    ['dd\\5464656646:this3', 'dd\\43543453:this2']
  ]
]

// 预处理构建文件名到路径的映射,仅在数组初始化/更新时执行一次
const filenameMap = {}
// flat(Infinity)会把任意层级的嵌套数组打平为一维数组,简化遍历逻辑
c.flat(Infinity).forEach(fullPath => {
  const fileName = fullPath.slice(fullPath.indexOf(':') + 1)
  if (!filenameMap[fileName]) {
    filenameMap[fileName] = []
  }
  // 同文件名的多条路径都会存入数组
  filenameMap[fileName].push(fullPath)
})

function test() {
  const input = document.getElementById('input').value.trim()
  const matchPaths = filenameMap[input]
  if (matchPaths) {
    // 可按需求打印所有匹配路径,或者取第一条等
    console.log('匹配到的路径:', matchPaths)
  } else {
    console.log("name not found")
  }
}
<input id="input">
<button onclick="test()">click</button>

如果需要兼容IE等不支持flat方法的环境,把c.flat(Infinity).forEach替换成你原有代码的多层forEach遍历逻辑即可,核心的映射表构建逻辑保持不变。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 03:36:07