JavaScript数组去重问题:localStorage商品数组添加时出现重复项
问题分析
原代码中使用some()方法的逻辑存在错误:some()会遍历数组,只要遇到第一个与当前商品名称不匹配的元素,就执行push操作添加新商品。比如数组已有[{productName: "001"}, {productName: "002"}],再次添加"002"时,遍历到第一个元素"001"就触发了push,完全忽略了数组中已存在的"002",导致重复项产生。
修复方案
核心逻辑改为:先检查数组中是否存在同名商品,存在则更新数量,不存在则添加新商品。使用find()方法精准定位目标元素,避免遍历过程中的误操作。
修复后的代码:
saveProducts(product) { // 从localStorage获取数组,为空则初始化为空数组 let originalProd = JSON.parse(localStorage.getItem("PRODUCT_ORIGINAL")) || []; // 查找是否存在同名商品 const existingItem = originalProd.find(item => item.productName === product.name); if (existingItem) { // 存在同名商品,更新数量(若数量不同) if (existingItem.productQuantity !== product.quantity) { existingItem.productQuantity = product.quantity; } // 可按需添加价格更新逻辑:existingItem.productPrice = product.price; } else { // 不存在则添加新商品 originalProd.push({ productName: product.name, productQuantity: product.quantity, productPrice: product.price }); } // 将更新后的数组保存回localStorage localStorage.setItem("PRODUCT_ORIGINAL", JSON.stringify(originalProd)); // 同步到originalProductToSave变量 this.originalProductToSave = [...originalProd]; }
关键优化点
- 替换
some()为find():find()直接返回匹配的元素(无匹配则返回undefined),能精准判断商品是否存在,避免遍历中途误添加重复项。 - 简化数组初始化:用
|| []处理localStorage返回null的情况,省去额外的null判断。 - 统一数据流向:直接操作从localStorage取出的数组,更新后保存回去,再同步到
originalProductToSave,逻辑更清晰不易出错。
内容的提问来源于stack exchange,提问作者Jack23
相关产品推荐
相关产品推荐

