javascript 有没有办法删除所有具有匹配特定模式的键的 sessionStorage 项目?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19844750/
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
Is there a way to remove all sessionStorage items with keys that match a certain pattern?
提问by Jesse Atkinson
Lets say my sessionStorage
contains three objects who's keys are foo
, foobar
, and baz
. Is there a way that I can call .removeItem
or somehow delete all items in sessionStorage
who's keys match foo
? In this example I'd be left with only the item who's key is baz
.
比方说,我sessionStorage
有三个对象是谁的键foo
,foobar
和baz
。有没有办法可以调用.removeItem
或以某种方式删除sessionStorage
who's keys match 中的所有项目foo
?在这个例子中,我只剩下关键是baz
.
回答by roland
Update September 20, 2014As pointed out by Jordan Trudgett the reverse loop is more appropriate
2014 年 9 月 20 日更新正如 Jordan Trudgett 所指出的,反向循环更合适
You can only achieve it programmatically as sessionStorage
exposes a limited set of methods: getItem(key)
, setItem(key, value)
, removeItem(key)
, key(position)
, clear()
and length()
:
您只能通过编程实现它sessionStorage
公开了一组有限的方法:getItem(key)
,setItem(key, value)
,removeItem(key)
,key(position)
,clear()
和length()
:
var n = sessionStorage.length;
while(n--) {
var key = sessionStorage.key(n);
if(/foo/.test(key)) {
sessionStorage.removeItem(key);
}
}
See Nicholas C. Zakas' blog entry for more details:
有关更多详细信息,请参阅 Nicholas C. Zakas 的博客条目:
http://www.nczonline.net/blog/2009/07/21/introduction-to-sessionstorage/
http://www.nczonline.net/blog/2009/07/21/introduction-to-sessionstorage/
回答by Pointy
You could do something like
你可以做类似的事情
Object.keys(sessionStorage)
.filter(function(k) { return /foo/.test(k); })
.forEach(function(k) {
sessionStorage.removeItem(k);
});
回答by petko
Since both local and sessionStorage are objects you can go through their properties like this:
由于 local 和 sessionStorage 都是对象,因此您可以像这样查看它们的属性:
for (var obj in localStorage) {
if (localStorage.hasOwnProperty(obj) && obj == "myKey") {
localStorage.removeItem(obj);
}
}
and remove the desired values by key, here it's "myKey" for example.
并通过键删除所需的值,例如这里是“myKey”。
回答by Shubham Takode
Try this:
试试这个:
angular.forEach(sessionStorage, function (item,key) {
sessionStorage.removeItem(key);
});
This will delete everything from sessionStorage
这将从 sessionStorage 中删除所有内容