【发布时间】:2022-07-06 15:04:22
【问题描述】:
以下代码处理文件路径列表,并且应该只返回 XML 文件的文件名(不带扩展名)。目前我得到了这个:
const filteredFiles = files
.map(f => f.match(/.*\/(.*)\.xml/)) // map to regex match with capture
.filter(v => v) // non-matches returned null and will be filtered out here
.map(m => m[1]) // map out the regex capture
我觉得这段代码很麻烦。有没有办法以更“有效”的方式结合匹配和过滤? “高效”是指代码可读高效而不是时间高效,因为输入数组最多保存 100 个值,但大部分时间在 10 到 20 之间。
【问题讨论】:
-
使用 foreach 并将更改的元素推送到 foreach 中的过滤文件可能是您想要的。我认为它的代码可读性更高。
-
如果正在寻找这种方式来优化您的代码,或者它应该只迭代一次。所以你可以使用
.reduce示例files.reduce((r, f) => { const value = f.match(/.*\/(.*)\.xml/); if (value?.[1]) { return [...r, value[1]]} return r;},[])
标签: javascript arrays ecmascript-6