簡體   English   中英

如何刪除javascript中的本地存儲

[英]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和時間戳的組合

可能是這樣的(因為我看到您正在使用該組合與key變量)

localStorage.removeItem(key);

如果它不起作用,您可以檢查您的瀏覽器以查看本地存儲的正確密鑰(右鍵單擊您的頁面和 select Inspect然后您可以查找Application選項卡)

在此處輸入圖像描述

如果你想刪除所有以前綴開頭的本地存儲項目(例如"diary" ),你可以像這樣使用 function :

TS游樂場

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM