数组元素存在则删除不存在则添加的代码逻辑错误修复咨询
修复数组遍历中的增删逻辑错误
问题根源
原代码存在三个核心问题:
- 循环越界:
n <= world.length会导致最后一次循环访问world[world.length],得到undefined,此时会执行添加操作,插入{id: undefined}的无效元素,这也是你看到"无论finished值如何都会添加元素"的主要原因。 - 全局变量污染:
n和ID未用let/const声明,会成为全局变量,引发意外的逻辑冲突。 - 冗余查找:先调用
find再调用_.findIndex,重复遍历数组,降低执行效率。
修复后的代码(使用Lodash)
for (let n = 0; n < world.length; n++) { const ID = world[n]; let finished = false; // 直接查找目标元素索引,合并重复操作 const index = _.findIndex(myArray, { "id": ID }); if (index > -1) { myArray.splice(index, 1); finished = true; } // 仅当未找到对应元素时执行添加 if (!finished) { myArray.push({ id: ID }); } }
原生JS实现方案(无需Lodash)
如果项目未引入Lodash,可改用原生findIndex方法:
for (let n = 0; n < world.length; n++) { const ID = world[n]; let finished = false; const index = myArray.findIndex(item => item.id === ID); if (index > -1) { myArray.splice(index, 1); finished = true; } if (!finished) { myArray.push({ id: ID }); } }
修复点说明
- 循环条件改为
n < world.length,确保只遍历数组的有效索引(从0到length-1),避免访问undefined。 - 用
let声明循环变量n,const声明ID,避免全局变量污染。 - 合并查找逻辑:直接通过一次索引查找完成存在性判断与定位,提升代码效率。
示例验证结果
针对你提供的示例数据,执行后最终myArray会变为:
[{"id": "12461667"}]
完全符合"存在则删除,不存在则添加"的需求。
内容的提问来源于stack exchange,提问作者verlager
相关产品推荐
相关产品推荐

