请勿删除本地存储的所有键

时间:2018-09-01 04:12:21

标签: javascript local-storage

在我的应用程序中,我希望我的本地存储中的所有键都将被删除,但所有包含“向导”一词的键除外。

诸如

的命令
localstorage.clear(); 

将删除所有内容,而我只想保留带有“ wizard”一词的内容,但是我遇到了错误,因为如果删除匹配项,则在下一次迭代中将跳过键,由于将其删除,我将得到一个错误,该错误试图在现在将为空的位置中搜索匹配项。我该怎么解决?

这是我的代码:

for ( var i = 0, len = localStorage.length; i < len; ++i ) {
  //if the key not contain the word "wizard" will be erased
  if( localStorage.getItem(localStorage.key(i)).search("wizard")==-1){
   localstorage.removeItem( localStorage.getItem( localStorage.key( i ) ) );
  }
}

3 个答案:

答案 0 :(得分:4)

您可以遍历entries的{​​{1}},如果值包含localStorage,则删除密钥:

wizard

结果:仅保留localStorage.foo = 'foo'; localStorage.bar = 'wizard1'; localStorage.baz = 'wizard2'; localStorage.buzz = 'buzz'; Object.entries(localStorage).forEach(([key, val]) => { if (!val.includes('wizard')) delete localStorage[key]; }); console.log(Object.keys(localStorage)); bar键。

(由于堆栈代码段不支持localStorage,因此无法发布为嵌入式代码段)

https://jsfiddle.net/cLm3kg01/

如果要保留包含baz键名而不是包含wizard,请改用wizard Object.keys中的键来迭代键:

Object.entries

https://jsfiddle.net/cLm3kg01/6/

答案 1 :(得分:0)

这样做:

for ( var i = 0, len = localStorage.length; i < len; ++i ) {
  //if the key not contain the word "wizard" will be erased
  if( localStorage.key(i).search("wizard")==-1){
   localstorage.removeItem( localStorage.key( i )  );
  }
}

如果您要搜索item的值,那么您的代码就可以了。但是您只需要使用带有全局标志的正则表达式:

.search(/wizard/g)

要移除这样的项目:

localstorage.removeItem( localStorage.key( i )  );

但不是这样:

localstorage.removeItem( localStorage.getItem( localStorage.key( i ) ) );

答案 2 :(得分:0)

localStorage中的所有项目复制到一个对象中,然后将其清除。然后将所需项目复制回localStorage

localStorage.setItem("test", 123); 
localStorage.setItem("wizard", 123); 
var keyToSave = "wizard";

function clearStorageWithoutKey(keyToSave){
   var items = {...localStorage};
   localStorage.clear();
   localStorage.setItem(keyToSave,items[keyToSave]);
   console.log(localStorage);
}
clearStorageWithoutKey(keyToSave);