清除JavaScript中的localStorage?

有没有办法重置/清除JavaScript中的浏览器的localStorage?

西里伽罗2020/03/11 11:57:36

To clear sessionStorage

sessionStorage.clear();
理查德路易2020/03/11 11:57:36
window.localStorage.clear(); //try this to clear all local storage
逆天乐2020/03/11 11:57:36

这是一个允许您删除所有localStorage项的函数,但有例外。您需要此功能的jQuery您可以下载要点

你可以这样称呼它

let clearStorageExcept = function(exceptions) {
  let keys = [];
  exceptions = [].concat(exceptions); // prevent undefined

  // get storage keys
  $.each(localStorage, (key) => {
    keys.push(key);
  });

  // loop through keys
  for (let i = 0; i < keys.length; i++) {
    let key = keys[i];
    let deleteItem = true;

    // check if key excluded
    for (let j = 0; j < exceptions.length; j++) {
      let exception = exceptions[j];
      if (key == exception) {
        deleteItem = false;
      }
    }

    // delete key
    if (deleteItem) {
      localStorage.removeItem(key);
    }
  }
};
宝儿Harry2020/03/11 11:57:36

如果要从用户的本地存储中删除特定的项目或变量,可以使用

localStorage.removeItem("name of localStorage variable you want to remove");
Harry小宇宙2020/03/11 11:57:36

使用此命令清除localStorage:

localStorage.clear();