[英]How to remove local storage in javascript
我正在研究 JavaScript 並且已經堅持了幾個星期。 我需要從本地存儲中刪除這些項目。 但是使用localStorage.removeItem('diary');
不管用。
// Make a demo text item
data =
"Friday: We arrived to this wonderful guesthouse after a pleasant journey " +
"and were made most welcome by the proprietor, Mike. Looking forward to " +
"exploring the area tomorrow.";
item = makeDiaryItem("text", data);
// Make a key using a fixed timestamp
key = "diary" + "1536771000001";
// Store the item in local storage
localStorage.setItem(key, item);
// Make a demo text item
data =
"Saturday: After a super breakfast, we took advantage of one of the many " +
"signed walks nearby. For some of the journey this followed the path of a " +
"stream to a charming village.";
item = makeDiaryItem("text", data);
// Make a key using a fixed timestamp
key = "diary" + "1536771000002";
// Store the item in local storage
localStorage.setItem(key, item);`
有人能指出我正確的方向嗎? 不尋找直接的答案。
您需要指定要從本地存儲中刪除的正確keyname
。
在您的代碼中,您使用鍵名“diary1536771000002”設置本地存儲中的項目。 但是,您正在嘗試刪除鍵名為“日記”的項目。
試試這個:
localStorage.removeItem('diary1536771000002');
如果你想刪除所有以前綴開頭的本地存儲項目(例如"diary"
),你可以像這樣使用 function :
function removeLocalStorageItems (matcher) {
const keys = [];
for (let i = 0; i < localStorage.length; i += 1) {
const key = localStorage.key(i);
if (key) keys.push(key);
}
const shouldRemove = typeof matcher === 'function' ? matcher : (str) => matcher.test(str);
for (const key of keys) {
if (shouldRemove(key)) localStorage.removeItem(key);
}
}
function removeLocalStorageItemsByPrefix (prefix) {
removeLocalStorageItems(key => key.startsWith(prefix));
}
// Use:
removeLocalStorageItemsByPrefix('diary');
// or
removeLocalStorageItems(/^diary/);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.