为什么这个没用通过样例 数组 js练习

在数组的专项练习中为什么我这个通不过
http://www.nowcoder.com/practice/a93dd26ebb8c425d844acc17bcce9411?tpId=6&tqId=10952&rp=1&ru=%2Fta%2Fjs-assessment&qru=%2Fta%2Fjs-assessment%2Fquestion-ranking

function removeWithoutCopy(arr, item) {
    arr.forEach(function(e){
      if(e==item){
          arr.splice(arr.indexOf(item),1);
      }
    });
    return arr;
}
全部评论
使用splice时,最好使用一个新数组保存结果,而且for循环的效率会比forEach高,另外forEach在循环中无法使用break和continue
点赞 回复
分享
发布于 2016-10-22 18:02
function removeWithoutCopy(arr, item) { arr.forEach(function (e) { if (e == item) { arr.splice(arr.indexOf(item), 1); arr.length--; } }); return arr; } 主要原因是,js数组调用splice方法删除数据后会重建数组索引,比如测试用例中的 removeWithoutCopy([1, 2, 2, 3, 4, 2, 2], 2),在删除前两个2之后,数组 的索引实际减少了2,导致在forEach方法中最后的两个2实际已经越界而无法删除。解决 方法如上,每次删除一个元素后手工把arr的length减1
点赞 回复
分享
发布于 2016-10-22 18:01
联想
校招火热招聘中
官网直投

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务