【问题标题】:How to remove specific item from local storage array?如何从本地存储阵列中删除特定项目?
【发布时间】:2017-07-05 17:11:44
【问题描述】:

我正在构建一个“待办事项列表”,用户在点击后将新笔记附加到列表中。

我将所有附加数据保存在本地存储中。

现在我想从数组中删除单击的注释并将其保存回本地存储。 我有这个代码:

    **//Here i get the note** 
    var getNote = JSON.parse(localStorage.getItem("savedNotes")) || [];
         $("#notes-section").append(getNote);

    **//Here i set the note** 
         getNote.push(note);
      localStorage.setItem("savedNotes", JSON.stringify(getNote)); 



 **//Here i want to remove the note from the array**
    $(document).on('click', '.pin', function() {
$(this).parent().css({opacity: 1.0, visibility: "visible"}).animate({opacity: 0}, 2000);

  for(var i =0 ; i < getNote.length; i++ ){

     getNote.splice(i,1);


       localStorage.setItem("savedNotes", JSON.stringify(getNote)); 
    }

});

【问题讨论】:

  • 你能把你的代码减少到 minimal reproducible example 吗?强调最小。
  • @evolutionxbox 谢谢,现在可以了吗? (我是新来的..)
  • 好多了。显示问题的简短示例可帮助人们更快、更准确地回答您的问题。

标签: javascript arrays local-storage


【解决方案1】:

如 cmets 所述,您只需要提供相关代码,但只是为了清除这里的内容,这里的方法是:

  • 要有一个空数组notes
  • 通过localStorage.setItem("savedNotes", JSON.stringify(notes))将此数组添加到localStorage
  • 每次添加注释时,您都需要:从 localStoragenotes = JSON.parse(localStorage.getItem("savedNotes")) 解析这个数组。
  • 然后通过notes.push(note)将新的note推送到这个数组中。
  • 然后用localStorage.setItem("savedNotes", JSON.stringify(notes))再次设置此项,它将更新您在localStorage中的现有项。

这一切都依赖于Storage.getItem()Storage.setItem() 方法。

要从数组中删除note,您需要做同样的事情,希望您会在解析后的数组中搜索此注释并将其删除。

【讨论】:

  • 感谢您的回答,但我仍然无法弄清楚如何做到这一点,请您说的更具体些吗?
  • 你需要遍历数组,找到要从数组中删除的项,你可以关注this
猜你喜欢
  • 1970-01-01
  • 2018-07-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多