checking for not null not working with localStorag

2020-05-10 23:55发布

问题:

var test = null;
if(test !== null){
    console.log('should not be logged in the console');//it worked
}


localStorage.setItem('foo',null);
console.log(localStorage.getItem('foo'));//logs null
if(localStorage.getItem('foo') !== null){
    console.log('should not be logged');//din't work, it's getting logged in the console
}

It seems the localStorage is storing the value null as string 'null'. So, the following code worked fine for me.

if(localStorage.getItem('foo') !== 'null'){

I have also ensured the code worked for me with setting the localStorage value something other than null.

This is actually not an answer. Because we may set localStorage value as string 'null' too. Not?

I know I can check like if(!variable){ but this will check for empty strings (""), null, undefined, false and the numbers 0 and NaN.

And there's a way to check for null only using like this:

if(variable === null && typeof variable === "object")

This might be a bug to Storage system? Is there any solution for checking actually null instead of 'null'?

回答1:

According to this answer:
Storing Objects in HTML5 localStorage

localStorage is made to save String key-value-pairs, only!

null is an empty Object.

So this is not a bug, it is actually the expected behaviour.



回答2:

You can only store string in the localStorage.

So, when you save null value in localStorage, you're actually storing "null"(string) in the localStorage.

To check if value in localStorage is null, use ==.

Example:

localStorage.setItem('foo', null);
console.log(localStorage.getItem('foo')); //logs null as string
console.log(typeof localStorage.getItem('foo')); //logs string

if (localStorage.getItem('foo') != null) {
//                              ^^         // Don't use strict comparison operator here
    console.log('Should work now!');
}