【问题标题】:Deletion by index of an article which is in an array of the localStorage vuejs按索引删除 localStorage vuejs 数组中的文章
【发布时间】:2021-08-15 02:30:29
【问题描述】:

我无法删除本地存储中的项目。我创建了一个表来存储添加的项目。我想通过它的索引或如果可能的话通过它的 id 来删除一篇文章。谢谢你的帮助

deleteOption(){
      this.test = JSON.parse(localStorage.getItem('test'))
      this.test.splice(index, 1)
},

test:[
   {
    id:1,
    item: test item 1
   },
   {
    id:2,
    item: test item 2
   },
   {
    id:3,
    item: test item 3
   },   
]


addItem () {

localStorage.setItem("test",JSON.stringify(this.test))

}


【问题讨论】:

    标签: javascript vue.js local-storage


    【解决方案1】:

    localstorage getItem 方法返回一个应该被解析为数组的字符串:

      this.test = JSON.parse(localStorage.getItem('test'))
      this.test.splice(index, 1)
    

    【讨论】:

    • 谢谢,它不起作用@boussadjra ,对于 (let i = 0; i
    • @tony 在您的示例中,i 是一个整数,它没有 splice 方法。如果您的数组被称为test,正确的方法(如@Boussadjra 所建议)是this.test.splice(...);
    • 感谢@Anis R 的回答,当我尝试这种方式时,我得到了回应:splice undefined and index undefined
    【解决方案2】:
    test = [
      {
        id: 1,
        item: "test item 1",
      },
      {
        id: 2,
        item: "test item 2",
      },
      {
        id: 3,
        item: "test item 3",
      },
    ];
    
    testNew = test.filter((item) => item.id !== 2);
    
    console.log(testNew);
    

    它将删除 id 为 2 的项目

    【讨论】:

    • 谢谢@Neel Debnath 的回答我会试试你的方法。
    【解决方案3】:

    在您的情况下需要:

    1. 检索您保存在本地存储中的字符串表示形式
    2. 将字符串解析成数组
    3. 修改数组
    4. 将数组转换回字符串
    5. 将转换后的字符串保存回本地内存。
    
    test:[
       {
        id:1,
        item: test item 1
       },
       {
        id:2,
        item: test item 2
       },
       {
        id:3,
        item: test item 3
       },   
    ]
    
    localStorage.setItem("test",JSON.stringify(this.test))
    
    
    function deleteByIndex(index)
    {
      var arr = JSON.parse(localStorage.getItem('test'));
      arr = arr.splice(index, 1);
      localStorage.setItem("test",JSON.stringify(arr))
    }
    
    function deleteById(id)
    {
      var arr = JSON.parse(localStorage.getItem('test'));
      arr = arr.filter(function(item) {
        return item.id !== id
       });
      localStorage.setItem("test",JSON.stringify(arr))
    }
    
    
    

    【讨论】:

    • 感谢@Alexander Higgins 的回答。对于索引修改,它一次性删除两个而不是正确的一个。有时它会将我作为拼接未定义错误发送给我。按 id 删除不起作用,没有任何反应。在做你给我的代码之前,我必须做一个循环吗?
    【解决方案4】:

    谁能告诉我,我无法在 localStorage 的数组中检索对象的索引?

    【讨论】:

      【解决方案5】:

      我已经尝试了几天,无法实现我想要的。我已经尝试了这篇文章中给我的所有方法。其中一种方法会删除我的所有内容,一旦我添加一个选项,我就会得到我删除的所有选项。

      【讨论】:

        猜你喜欢
        • 2021-08-18
        • 2019-11-19
        • 2012-04-22
        • 2014-05-04
        • 1970-01-01
        • 2020-01-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多