在javascript中清除localStorage?

本文翻译自:Clearing localStorage in javascript?

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


#1楼

参考:https://stackoom.com/question/WAmk/在javascript中清除localStorage


#2楼

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

localStorage.removeItem("name of localStorage variable you want to remove");

#3楼

Here is a function that will allow you to remove all localStorage items with exceptions. 这是一个允许您删除所有localStorage项目的函数。 You will need jQuery for this function. 你需要jQuery来实现这个功能。 You can download the gist . 你可以下载要点

You can call it like this 你可以这样称呼它

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);
    }
  }
};

#4楼

First things first, you need to check to make sure that localStorage is enabled. 首先,您需要检查以确保启用了localStorage。 I would recommend doing it like this: 我建议这样做:

var localStorageEnabled = false;
try { localStorageEnabled = !!localStorage; } catch(e) {};

Yes, you can (in some cases) just check to see if the localStorage is a member of the window object. 是的,您可以(在某些情况下)检查localStorage是否是窗口对象的成员。 However, there are iframe sandboxing options (among other things) that will throw an exception if you even attempt to access the index 'localStorage'. 但是,如果您甚至尝试访问索引“localStorage”,则会有iframe沙盒选项(以及其他内容)抛出异常。 Thus, for best-practices reasons, this is the best way to check to see if the localStorage is enabled. 因此,出于最佳实践原因,这是检查localStorage是否已启用的最佳方法。 Then, you can just clear the localStorage like so. 然后,您可以像这样清除localStorage。

if (localStorageEnabled) localStorage.clear();

For example, you could clear the localStorage after an error occurs in webkit browsers like so. 例如,您可以在webkit浏览器中发生错误后清除localStorage。

// clears the local storage upon error
if (localStorageEnabled)
  window.onerror = localStorage.clear.bind(localStorage);

In the above example, you need the .bind(window) because without it, the localStorage.clear function will run in the context of the window object, instead of the localStorage object making it silently fail. 在上面的示例中,您需要.bind(window)因为没有它, localStorage.clear函数将在window对象的上下文中运行,而不是localStorage对象使其无声地失败。 To demonstrate this, look at the below example: 为了证明这一点,请看下面的例子:

window.onerror = localStorage.clear;

is the same as: 是相同的:

window.onerror = function(){
    localStorage.clear.call(window);
}

#5楼

localStorage.clear();

or 要么

window.localStorage.clear();

to clear particular item 清除特定项目

window.localStorage.removeItem("item_name");

To remove particular value by id : 要通过id删除特定值:

var item_detail = JSON.parse(localStorage.getItem("key_name")) || [];           
            $.each(item_detail, function(index, obj){
                if (key_id == data('key')) {
                    item_detail.splice(index,1);
                    localStorage["key_name"] = JSON.stringify(item_detail);
                    return false;
                }
            });

#6楼

Localstorage is attached on the global window . Localstorage附加在全局window When we log localstorage in the chrome devtools we see that it has the following APIs: 当我们在chrome devtools中记录localstorage时,我们看到它有以下API:

在此输入图像描述

We can use the following API's for deleting items: 我们可以使用以下API来删除项目:

  1. localStorage.clear() : Clears the whole localstorage localStorage.clear() :清除整个localstorage
  2. localStorage.removeItem('myItem') : To remove individual items localStorage.removeItem('myItem') :删除单个项目
  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
JavaScript,`sessionStorage` 和 `localStorage` 是两种用于在浏览器会话期间存储数据的本地存储机制。它们的区别在于: - `sessionStorage` 保存的数据只会在当前会话(即同一窗口或标签页)存在,关闭浏览器或标签页后数据会被清除。 - `localStorage` 则持久化存储,即使在关闭浏览器后,数据也会保留,直到手动清除。 下面是设置和读取这两个存储的简单示例: ### 设置数据 1. 使用 `setItem()` 方法存储键值对: ```javascript // sessionStorage 示例 sessionStorage.setItem('username', 'JohnDoe'); // localStorage 示例 localStorage.setItem('cartItems', JSON.stringify([{ item: 'apple', quantity: 3 }])); // 存储JSON格式数据 ``` ### 读取数据 2. 使用 `getItem()` 方法获取特定键的数据: ```javascript // 从 sessionStorage 获取 const sessionStorageUsername = sessionStorage.getItem('username'); console.log(sessionStorageUsername); // 输出:'JohnDoe' // 从 localStorage 获取 const cartItemsStr = localStorage.getItem('cartItems'); if (cartItemsStr) { const cartItems = JSON.parse(cartItemsStr); // 解析成对象 console.log(cartItems); } ``` ### 删除数据 3. 使用 `removeItem()` 方法删除存储的数据: ```javascript // 删除 sessionStorage 的值 sessionStorage.removeItem('username'); // 删除 localStorage 的值 localStorage.removeItem('cartItems'); ``` ### 清空整个存储 4. 若要清空整个存储,可以使用 `clear()` 方法: ```javascript // 清空 sessionStorage sessionStorage.clear(); // 清空 localStorage localStorage.clear(); ```
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值