我有这个代码
function deleteElement() {
const myArray = map(listItems, getText);
var elementToDelete =document.getElementById('deleteElement').value;
const index = myArray.findIndex((item) => item.includes(elementToDelete));
if (index > -1) {
// delete and update local storage
console.log("found element and index ", index);
let moment = localStorage.getItem('pelis_guardades');
let deleted = moment.splice(index, 1);
localStorage.setItem('pelis_guardades', JSON.stringify(deleted))
console.log(deleted);
}
}
我已经找到了要删除的数组元素的索引,一切都很好,但是现在我想“更新”本地存储以从索引中删除项目。
我可以删除加载到本地存储中的阵列上的特定值。叫做myArray。
const myArray = map(listItems, getText);
myArray包含“原始字符串数据”,然后通过“原始字符串数据”将其放置在本地存储中,
localStorage.setItem('things',JSON.stringify(myArray));
如何从localStorage中删除?
我尝试过,在本地存储上使用splice方法,但是不起作用!
谢谢!
答案 0 :(得分:0)
尝试将moment变量解析为JSON 使用
修改
function deleteElement() {
const myArray = map(listItems, getText);
var elementToDelete =document.getElementById('deleteElement').value;
const index = myArray.findIndex((item) => item.includes(elementToDelete));
if (index > -1) {
// delete and update local storage
console.log("found element and index ", index);
let moment = localStorage.getItem('pelis_guardades');
//try to add this code
let moment_parse = JSON.parse(moment);
let deleted = moment_parse.splice(index, 1);//edit
localStorage.setItem('pelis_guardades', JSON.stringify(deleted))
console.log(deleted);
}
在拼接 moment变量
之前答案 1 :(得分:0)
问题是您使用Array.splice
时出错。
此方法使给定的数组变异。
您不需要splice
操作的结果。相反,您必须将数组作为新值传递来更新本地存储。
// 1. read value
const moment = JSON.parse(localStorage.getItem('pelis_guardades'))
// 2. mutate given array by removing one element from index.
moment.splice(index, 1);
// 3. write value
localStorage.setItem('pelis_guardades', JSON.stringify(moment))