javascript 从本地存储中清除对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9566276/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 07:04:08  来源:igfitidea点击:

clearing objects from localstorage

javascripthtmllocal-storage

提问by Alex

with localstorage i have a load of unspecified items saved with dynamic names using a data namespace like so:

使用 localstorage,我有大量未指定的项目,使用动态名称保存,使用数据命名空间,如下所示:

localStorage["myAppName.settings.whatever"] = something.whatever; 

//and this:
localStorage["myAppName.data."+dynObj.name] = dynObj.data;

I want to keep the settings but not the data. However I won't ever know what all of the names inside of my data object are so I cannot clear them individually. I need to clear these each time my app is loaded but I must keep the settings so localstorage.clear()is not an option.

我想保留设置但不保留数据。但是,我永远不会知道我的数据对象中的所有名称是什么,因此我无法单独清除它们。每次加载我的应用程序时,我都需要清除这些,但我必须保留这些设置,所以 localstorage.clear()不是一个选项。

I have tried:

我努力了:

localstorage.removeItem("myAppName.data")

but no dice.

但没有骰子。

Anyone have any thoughts on how to clear dynamically named portions of localstorage?

有人对如何清除本地存储的动态命名部分有任何想法吗?

回答by Niklas

You can loop through the keys in the localStorage and target them with a reg exp:

您可以遍历 localStorage 中的键并使用 reg exp 将它们作为目标:

Object.keys(localStorage)
      .forEach(function(key){
           if (/^(myAppName.data.)/.test(key)) {
               localStorage.removeItem(key);
           }
       });  

Here's a similar question: HTML5 Localstorage & jQuery: Delete localstorage keys starting with a certain word

这是一个类似的问题:HTML5 Localstorage & jQuery: Delete localstorage keys starts with a specific word

回答by Fabrizio Calderan

try something like

尝试类似的东西

var i = localStorage.length, key;
while (i--) {
  key = localStorage.key(i);
  if (key.slice(0, 19) !== "myAppName.settings.") {
    localStorage.remove(key);
  }
}

回答by Stefan

Tried something like this?

尝试过这样的事情吗?

// Select current settings
var settings = localStorage["myAppName.settings"] || {};
// Clear localStorage
localStorage.clear();
// Add settings to localStorage
localStorage["myAppName.settings"] = settings;

回答by Dorian

Assuming a this.namespacepresent (in my case 'session') and the underscore library:

假设一个this.namespace礼物(在我的例子中'session')和下划线库:

_.each(_.keys(localStorage), function(key) {
  if (RegExp("^" + this.namespace + "\.").test(key)) {
    return localStorage.removeItem(key);
  }
});

And with CoffeeScript:

并使用 CoffeeScript:

_.each _.keys(localStorage), (key) ->
  if ///^#{@namespace}\.///.test(key)
    localStorage.removeItem(key)