Javascript 如何删除和清除所有 localStorage 数据
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10710674/
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
How to remove and clear all localStorage data
提问by itsme
I need to clear all data i set into localStorage
. By this, I mean completely reset localStorage
to null
when users remove their accounts.
我需要清除我设置的所有数据localStorage
。我的意思是完全重置localStorage
为null
用户删除其帐户的时间。
How can i do that with a simple function?
我怎么能用一个简单的功能做到这一点?
I tried this:
我试过这个:
function clearLocalStorage(){
return localStorage= null;
}
But it doesn't work as expected.
但它没有按预期工作。
回答by Lyn Headley
localStorage.clear();
localStorage.clear();
should work.
应该管用。
回答by Talha
If you want to remove/clean all the values from local storage than use
如果您想从本地存储中删除/清除所有值而不是使用
localStorage.clear();
And if you want to remove the specific item from local storage than use the following code
如果您想从本地存储中删除特定项目,请使用以下代码
localStorage.removeItem(key);
回答by John
It only worked for me in Firefox when accessing it from the window
object.
当从window
对象访问它时,它只对我在 Firefox 中工作。
Example...
例子...
window.onload = function()
{
window.localStorage.clear();
}
回答by iOSAndroidWindowsMobileAppsDev
Using .one
ensures this is done only once and not repeatedly.
使用.one
确保只执行一次而不是重复执行。
$(window).one("focus", function() {
localStorage.clear();
});
It is okay to put several document.ready event listeners (if you need other events to execute multiple times) as long as you do not overdo it, for the sake of readability.
可以放几个 document.ready 事件监听器(如果你需要其他事件多次执行),只要你不要过度,为了可读性。
.one
is especially useful when you want local storage to be cleared only once the first time a web page is opened or when a mobile application is installed the first time.
.one
当您希望仅在第一次打开网页或第一次安装移动应用程序时清除本地存储时,此功能特别有用。
// Fired once when document is ready
$(document).one('ready', function () {
localStorage.clear();
});
回答by Elliot Bonneville
Something like this should do:
这样的事情应该做:
function cleanLocalStorage() {
for(key in localStorage) {
delete localStorage[key];
}
}
Be careful about using this, though, as the user may have other data stored in localStorage
and would probably be pretty ticked if you deleted that. I'd recommend either a) not storing the user's data in localStorage
or b) storing the user's account stuff in a single variable, and then clearing that instead of deleting all the keys in localStorage
.
但是,使用它时要小心,因为用户可能存储了其他数据,localStorage
如果您删除它,可能会被打勾。我建议 a) 不将用户的数据存储在localStorage
或 b) 将用户的帐户内容存储在单个变量中,然后清除它而不是删除localStorage
.
Edit: As Lyn pointed out, you'll be good with localStorage.clear()
. My previous points still stand, however.
编辑:正如 Lyn 指出的那样,你会很好地使用localStorage.clear()
. 然而,我之前的观点仍然成立。