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

我有一些物品,我通过将它们与它们的 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(',') : [];


});



临摹微笑
浏览 262回答 2
2回答

开满天机

永远记住数组方法是你的朋友。array.prototype.find()一种方法是将with的使用结合起来,array.prototype.splice()如下所示:cartItems.find( ( item, i ) => {   if ( item == this_id ) {      cartItems.splice( i, 1 );      return true;   }   return false;} );这样,它只会删除它遇到的第一个匹配项目。

慕的地8271018

你的问题是使用本地存储,一旦你存储 ID 数组,它就会以数组的形式存储,同时检索你需要获取字符串 json 解析它的数据,然后运行所需的操作。检查这个例如。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript