为了账号安全,请及时绑定邮箱和手机立即绑定

如何仅删除在 localStorage 中多次出现的一个特定数据

如何仅删除在 localStorage 中多次出现的一个特定数据

临摹微笑 2023-02-24 16:04:32
我有一些物品,我通过将它们与它们的 ID 一起存储在 localStorage 中来添加到购物车。$(document).on('click', '.set-cart-info', function () {    // We retrieve the product id which is stored in the url    var url_id = window.location.search;    var id = url_id.split('?id=').pop();    // We retrieve the data from the localStorage    var cartItems = localStorage.getItem('teddy_id');    // If there is no data, we create an array    cartItems = cartItems ? cartItems.split(',') : [];    // Add the new data to the array    cartItems.push(id);    // We save the data in the localStorage    localStorage.setItem('teddy_id', cartItems.toString());});在 console.log 我得到这个:localStorage.getItem('teddy_id')"5beaacd41c9d440000a57d97,5beaabe91c9d440000a57d96,5beaabe91c9d440000a57d96,5beaaa8f1c9d440000a57d95,5beaabe91c9d440000a57d96,5beaaa8f1c9d440000a57d95,5beaabe91c9d440000a57d96,5beaacd41c9d440000a57d97,5beaaa8f1c9d440000a57d95,5beaaa8f1c9d440000a57d95,5beaaa8f1c9d440000a57d95,5beaabe91c9d440000a57d96,5beaacd41c9d440000a57d97,5beaacd41c9d440000a57d97,5beaacd41c9d440000a57d97,5beaacd41c9d440000a57d97,5beaacd41c9d440000a57d97,5beaaa8f1c9d440000a57d95"然后,我添加了通过检索产品 ID 并将其添加到 localStorage 来添加或删除产品数量的可能性,我的问题如下:当我检索 ID 以在 localStorage 中获取它时,它会删除所有项目这个 ID,我希望它只删除一个。这是允许添加数量的代码,以及应该修改的代码,以便它也只删除一个:$(document).on('click', '.add_qty', function () {    // We retrieve the product id which is stored in the class    var split_class = this.className.split(' ');    var this_id = split_class[1];    var cartItems = localStorage.getItem('teddy_id');    cartItems = cartItems ? cartItems.split(',') : [];    cartItems.push(this_id);    localStorage.setItem('teddy_id', cartItems.toString());});$(document).on('click', '.remove_qty', function () {    // We retrieve the product id which is stored in the class    var split_class = this.className.split(' ');    var this_id = split_class[1];    var cartItems = localStorage.getItem('teddy_id');    cartItems = cartItems ? cartItems.split(',') : [];});
查看完整描述

2 回答

?
开满天机

TA贡献1786条经验 获得超13个赞

永远记住数组方法是你的朋友。array.prototype.find()一种方法是将with的使用结合起来,array.prototype.splice()如下所示:


cartItems.find( ( item, i ) => {

   if ( item == this_id ) {

      cartItems.splice( i, 1 );

      return true;

   }

   return false;

} );

这样,它只会删除它遇到的第一个匹配项目。


查看完整回答
反对 回复 2023-02-24
?
慕的地8271018

TA贡献1796条经验 获得超4个赞

你的问题是使用本地存储,一旦你存储 ID 数组,它就会以数组的形式存储,同时检索你需要获取字符串 json 解析它的数据,然后运行所需的操作。检查这个例如



查看完整回答
反对 回复 2023-02-24
  • 2 回答
  • 0 关注
  • 261 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号