V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
banxi1988
V2EX  ›  前端开发

在循环数组时修改数组可以接受吗?

  •  
  •   banxi1988 ·
    banxi1988 · 2018-07-05 21:11:19 +08:00 · 1386 次点击
    这是一个创建于 2114 天前的主题,其中的信息可能已经有所发展或是发生改变。

    看到 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 的特殊的对象。

    2 条回复    2018-07-06 16:15:17 +08:00
    noe132
        1
    noe132  
       2018-07-06 08:23:42 +08:00
    其实怎么写都没问题,影响也不是很大。

    很多时候都是看心情罢了。
    jedihy
        2
    jedihy  
       2018-07-06 16:15:17 +08:00 via iPhone
    作者很清楚的指出了你的问题。遍历多次数组而且有拷贝。原方法可读性并不差。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5703 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 23ms · UTC 02:38 · PVG 10:38 · LAX 19:38 · JFK 22:38
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.