检查not null不使用localStorage

Bho*_*yar -3 javascript html5 local-storage

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
}
Run Code Online (Sandbox Code Playgroud)

似乎localStorage将值null存储为字符串'null'.所以,以下代码对我来说很好.

if(localStorage.getItem('foo') !== 'null'){
Run Code Online (Sandbox Code Playgroud)

我还确保代码适用于我将localStorage值设置为null以外的值.

这实际上不是一个答案.因为我们也可以将localStorage值设置为字符串'null'.不?

我知道我可以检查,if(!variable){但这将检查空字符串(""),null,undefined,false和数字0和NaN.

并且有一种方法只使用这样检查null:

if(variable === null && typeof variable === "object")
Run Code Online (Sandbox Code Playgroud)

这可能是存储系统的一个错误?是否有任何解决方案实际上检查null而不是'null'?

Tus*_*har 6

您只能存储string在 localStorage 中。

所以,当你保存null在localStorage的值,你实际上存储"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!');
}
Run Code Online (Sandbox Code Playgroud)


B. *_*mer 6

根据这个答案:
在HTML5 localStorage中存储对象

localStorage的是由保存字符串键值对,只有!

null是一个空对象.

所以这不是一个bug,它实际上是预期的行为.