Javascript 通过索引删除本地存储VUEJ数组中的项目
我无法删除localStorage中的项目。我创建了一个表来存储添加的项。我想通过索引或id删除文章。谢谢您的帮助Javascript 通过索引删除本地存储VUEJ数组中的项目,javascript,vue.js,local-storage,Javascript,Vue.js,Local Storage,我无法删除localStorage中的项目。我创建了一个表来存储添加的项。我想通过索引或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
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))
}
localstorage
getItem
方法返回应解析为数组的字符串:
this.test = JSON.parse(localStorage.getItem('test'))
this.test.splice(index, 1)
它将删除id为2的项目。您需要:
测试:[
{
id:1,
项目:试验项目1
},
{
id:2,
项目:测试项目2
},
{
id:3,
项目:测试项目3
},
]
setItem(“test”,JSON.stringify(this.test))
函数deleteByIndex(索引)
{
var arr=JSON.parse(localStorage.getItem('test');
arr=arr.拼接(索引,1);
setItem(“test”,JSON.stringify(arr))
}
函数deleteById(id)
{
var arr=JSON.parse(localStorage.getItem('test');
arr=arr.filter(功能(项目){
return item.id!==id
});
setItem(“test”,JSON.stringify(arr))
}
谁能告诉我,因为我无法在本地存储中检索数组中对象的索引?我已经尝试了几天,无法实现我想要的。我已经尝试了这篇文章中给我的所有方法。其中一个方法删除了我的所有内容,只要我添加一个选项,我就会得到我删除的所有选项。谢谢,它在@boussadjra不起作用,因为(让I=0;II
是一个整数,它没有splice
方法。如果您的数组被称为test
,正确的方法(如@Boussadjra所建议的)是this.test.splice(…)代码>谢谢@Anis R的回答,当我尝试这种方式时,我得到了一个回应:拼接未定义和索引未定义谢谢@Alexander Higgins的回答。对于索引修改,它一次删除两个,而不是正确的一个。有时它会以未定义错误的形式发送给我。按id删除不起作用,什么也没发生。在做你给我的代码之前,我需要做一个循环吗?谢谢@Neel Debnath的回答,我会试试你的方法。
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);