checking for not null not working with localStorage
This question already has an answer here:
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.
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!');
}
链接地址: http://www.djcxy.com/p/27932.html