我有一个存储在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>
答案 0 :(得分:1)
您需要使用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));
}
答案 1 :(得分:0)
我想你想要这个。
Click here
希望它能起作用,否则会有所帮助。enter code here