sessionStorage setItem returns true or false

我的未来我决定 提交于 2019-12-25 04:43:19

问题


I'm trying to figure out what the setItem method from sessionStorage returns. As far as I could get, the following code returns 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?


回答1:


Take a look at the sessionStorage specification.

This line:

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

Tells us setItem doesn't return anything. (void is the return value, there)


You can check if the item was set like this:

if (sessionStorage.getItem('myValue') == null){
    // myValue was not set
}else{
    // myValue was set
}



回答2:


Here is a guide on sessionStorage from the Mozilla Developer Network. It appears that sessionStorage.setItem(name, value) does not return anything.

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. */
}



回答3:


Use try catch expression, since the method throws an exception if the session is full, as stated in the specification :

try { sessionStorage.setItem('foo', 'bar'); }
catch(oops) {
     // maybe no more space, try to free
     localStorage.removeItem('foo');
     sessionStorage.setItem('foo', 'bar');
}


来源:https://stackoverflow.com/questions/21481856/sessionstorage-setitem-returns-true-or-false

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!