javascript sessionStorage setItem 返回 true 或 false
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21481856/
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
sessionStorage setItem returns true or false
提问by darksoulsong
I'm trying to figure out what the setItem
method from sessionStorage
returns. As far as I could get, the following code returns undefined
:
我试图弄清楚返回的setItem
方法是什么sessionStorage
。据我所知,以下代码返回undefined
:
var set = sessionStorage.setItem('foo', 'bar');
console.log(set);
I need to know if the item was successfully set or if it failed. How can I accomplish this without knowing the return?
我需要知道该项目是成功设置还是失败。我怎样才能在不知道回报的情况下做到这一点?
回答by Cerbrus
Take a look at the sessionStorage
specification.
看一下sessionStorage
规范。
This line:
这一行:
setter creator void setItem(DOMString key, DOMString value);
Tells us setItem
doesn't return anything. (void
is the return value, there)
告诉我们setItem
不返回任何东西。(void
是返回值,有)
You can check if the item was set like this:
您可以检查该项目是否设置如下:
if (sessionStorage.getItem('myValue') == null){
// myValue was not set
}else{
// myValue was set
}
回答by War10ck
Hereis a guide on sessionStorage
from the Mozilla Developer Network. It appears that sessionStorage.setItem(name, value)
does not return anything.
这是sessionStorage
来自 Mozilla Developer Network的指南。似乎sessionStorage.setItem(name, value)
没有返回任何东西。
However, if you manually wanted to check, you could try something like this:
但是,如果您想手动检查,则可以尝试以下操作:
sessionStorage.setItem('make', 'Ford');
/* Returns null if it cannot find the item in sessionStorage. */
if(sessionStorage.getItem('make')) {
/* Session storage set successfully. */
} else {
/* Session storage did not set successfully. */
}
回答by Jisay
Use try catch expression, since the method throws an exception if the session is full, as stated in the specification:
使用 try catch 表达式,因为如果会话已满,该方法会抛出异常,如规范中所述:
try { sessionStorage.setItem('foo', 'bar'); }
catch(oops) {
// maybe no more space, try to free
localStorage.removeItem('foo');
sessionStorage.setItem('foo', 'bar');
}