[英]Delete specific string from Local Storage array
我有這個代碼
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 中刪除?
我試過了,本地存儲上的拼接方法還是不行!!
謝謝!
嘗試使用將矩變量解析為 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);
}
在拼接矩變量之前
問題是您在使用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))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.