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
点赞 1

相关推荐

牛客热帖

牛客网
牛客企业服务