点击开关移除localStorage指定项时误删全部内容的技术问题
解决localStorage中移除指定coinId项的问题
你当前代码的问题很明确:取消开关选择时,直接调用localStorage.removeItem('checkedCoins')会删掉整个存储的数组,而非仅移除当前取消的coinId对应条目。要实现精准移除,按以下逻辑修改即可:
- 先从localStorage取出已有的checkedCoins数组
- 过滤掉与当前取消的coinId匹配的项
- 将过滤后的新数组重新存回localStorage(若数组为空,可选择移除整个存储项,避免存空数组)
修改后的完整代码:
function switchClick(event) { const coinId = event.currentTarget.id; const jsonString = localStorage.getItem("checkedCoins"); let cryptoCoins = jsonString ? JSON.parse(jsonString) : []; if(event.target.checked){ // 先检查是否已存在该coinId,避免重复添加 const isExists = cryptoCoins.some(item => item.id === coinId); if(!isExists){ cryptoCoins.push({id: coinId}); localStorage.setItem("checkedCoins", JSON.stringify(cryptoCoins)); if(cryptoCoins.length > 6 ) { alert("delete") } } } else { // 过滤掉当前要取消的coinId cryptoCoins = cryptoCoins.filter(item => item.id !== coinId); if(cryptoCoins.length > 0){ localStorage.setItem("checkedCoins", JSON.stringify(cryptoCoins)); } else { // 数组为空时移除整个存储项 localStorage.removeItem("checkedCoins"); } } }
额外优化了添加逻辑:先判断当前coinId是否已存在,避免数组中出现重复条目。
内容的提问来源于stack exchange,提问作者Dolbolob
相关产品推荐
相关产品推荐

