[英]How to remove item from localStorage array?
我有一個存儲在 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("問候語". 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));
}
我想你想要這個。 單擊此處希望它有效,否則會有所幫助。 enter code here
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.