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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 21:00:38  来源:igfitidea点击:

sessionStorage setItem returns true or false

javascripthtmlsessionstorage

提问by darksoulsong

I'm trying to figure out what the setItemmethod from sessionStoragereturns. 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 sessionStoragespecification.

看一下sessionStorage规范

This line:

这一行:

setter creator void setItem(DOMString key, DOMString value);

Tells us setItemdoesn't return anything. (voidis 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 sessionStoragefrom 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');
}