检查not null不使用localStorage [英] checking for not null not working with localStorage

查看:164
本文介绍了检查not null不使用localStorage的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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'。所以,下面的代码对我来说很好。

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'){

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

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

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

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

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

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

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

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

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

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

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

推荐答案

根据这个答案:

在HTML5 localStorage中存储对象

localStorage用于保存字符串键值对,

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

null是一个空对象。

null is an empty Object.

所以这不是错误,实际上是预期的行为。

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

这篇关于检查not null不使用localStorage的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆