我有一个存储在localStorage中的数组。单击按钮后,我希望删除数组中的项目,然后再次将其保存到localStorage中。这就是我的意思。
var greetings = ["Hello", "Hi", "Sup", "Hey"]
localStorage.setItem("greetings", JSON.stringify(greetings))
function remove() {
//remove "hi" How do I do this?
}
<button onclick="remove()">Remove</button>
最佳答案
您需要使用localStorage.getItem('greetings')从数组中获取项目,然后需要使用JSON.parse(array)解析字符串,因为localstorage项目始终是字符串。然后,您需要过滤出首选的字符串:array.filter(item => item!=='Hello'),然后最终更新本地存储:localStorage.setItem(“ greetings”,JSON.stringify(updatedArray)
const greetings = ["Hello", "Hi", "Sup", "Hey"];
localStorage.setItem("greetings", JSON.stringify(greetings));
function remove() {
const greetings = JSON.parse(localStorage.getItem("greetings"));
const filtered = greetings.filter(item => item !== 'Hello');
localStorage.setItem("greetings", JSON.stringify(filtered));
}