简体   繁体   中英

sessionStorage - set Item to null

I check if a sessionStorage Variable is null, and if true initialize it with "BAR". Otherwhise there should appear a console message with the value of the variable.

 sessionStorage.setItem("Foo", null); //I know this would make no sense at this part, this is just here for demo. if (sessionStorage.getItem("Foo") == null) { sessionStorage.setItem("Foo", "BAR"); } else { console.log("Foo != null (proof = '", sessionStorage.getItem("Foo"), "')"); } 

However, It always goes to the else statement and i get the console message which is telling me that the variable is "null", but if it is really "null" then why it is not initialized with "BAR"?

Per your edit, setItem requires the value passed in to be a string (a DOMString to be precise), anything else will be coerced to a string.

In your case, you pass in null , which is coerced to "null" . When you call getItem , you get a string back, which isn't null , so your code falls into the else block.

If you actually want to clear out an item from storage, the correct method to use is removeItem :

sessionStorage.removeItem("Foo");

Calling getItem now would result in a return value of null , not "null" .

HTML5 storage: sessionStorage or localStorage accepts a string. If a string value is not passed it will convert it to string and save. Hence we should convert the value to string using (JSON.stringify(value)) and after fetching we should again convert it to the original value.

var val = null;
//save to storage
sessionStorage.setItem('a',JSON.stringify(val));

//fetch from storage
var stringValue = sessionStorage.getItem('a');  //outputs "null"
var originalValue = JSON.parse(sessionStorage.getItem('a')); //outputs null

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM