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
}
似乎localStorage将值null存储为字符串' null'。所以,以下代码对我来说很好。
if(localStorage.getItem('foo') !== 'null'){
我还确保代码可以为我设置localStorage值而不是null。
这实际上不是答案。因为我们可以将localStorage值设置为字符串' null'太。不?
我知道我可以检查if(!variable){
,但这会检查空字符串(""),null,undefined,false以及数字0和NaN。
只有这样才能检查null:
if(variable === null && typeof variable === "object")
这可能是存储系统的错误?是否有任何解决方案用于检查实际为null而不是' null'?
答案 0 :(得分:6)
根据这个答案:
Storing Objects in HTML5 localStorage
localStorage用于保存字符串键值对,仅!
null是一个空对象。
所以这不是一个错误,它实际上是预期的行为。
答案 1 :(得分:4)
您只能将string
存储在localStorage中。
因此,当您在localStorage中保存null
值时,您实际上会在"null"
中存储localStorage
(字符串)。
要检查localStorage
中的值是否为null
,请使用==
。
示例:
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!');
}