看到 vue-router 中有下面这么一段代码:
// ensure wildcard routes are always at the end
for (let i = 0, l = pathList.length; i < l; i++) {
if (pathList[i] === '*') {
pathList.push(pathList.splice(i, 1)[0])
l--
i--
}
}
我感觉边循环数组边修改数组有点怪异。于是进行了如下修改。
// ensure wildcard routes are always at the end
const normalPathList = pathList.filter(it => it !== '*')
const wildcardPathList = pathList.filter(it => it === '*')
pathList.length = 0
pathList.push(...normalPathList)
pathList.push(...wildcardPathList)
然后提了个 Pull Request
意外被拒绝了:
Thanks for your concern! However, this solution goes through the original array multiple times and create multiple arrays
其实呢也就增加了两三次的循环,但是对对于一个前端 pathList 数组来说,数量一般也就 10 多个,或者 100 以内。 多循环一两次没什么大问题。 如果是我的项目的话,我倾向于可读性更好的代码。
不过对于 JavaScript 来说,其实数组并不是数组,跟 Java List 也不一样,而是一个使用索引作为 key 的特殊的对象。