[英]javascript null comparison different on chrome and firefox
I have the following code: 我有以下代码:
var a=sessionStorage.getItem("Token");
alert(a==null);
The returned value is null
(If I alert(a)
it displays null
). 返回的值为
null
(如果我alert(a)
则显示null
)。 The problem is that the alert(a==null)
display is TRUE on firefox and FALSE on safari and chrome. 问题是在firefox上的
alert(a==null)
显示为TRUE,而在野生动物园和Chrome上的显示为FALSE。 WTH? 什么 I have tried
a===null
with the same results as well as !a. 我已经尝试过
a===null
和!a一样的结果。
What am I doing wrong or what am I not aware of? 我在做错什么或我不知道什么?
Thanks for any help. 谢谢你的帮助。
You said in a comment: "I set Token with sessionStorage.setItem("Token",null);
" 您在评论中说: “我使用
sessionStorage.setItem("Token",null);
设置了令牌 ”
I believe the problem is that you are supposed to use session storage to store strings. 我相信问题是您应该使用会话存储来存储字符串。 When you pass
null
to setItem()
it converts it to a string "null"
. 将
null
传递给setItem()
,会将其转换为字符串"null"
。 Then when you retrieve it with getItem()
you get back this string "null"
which is of course not equal to an actual null
value. 然后,当使用
getItem()
检索它时,您将获得此字符串"null"
,该字符串当然不等于实际的null
值。
You can see this behaviour here: http://jsfiddle.net/CWVww/1/ 您可以在这里看到此行为: http : //jsfiddle.net/CWVww/1/
If you want to remove a previously set item then do this: 如果要删除先前设置的项目,请执行以下操作:
sessionStorage.removeItem("Token");
...and then calls to .getItem("Token")
will return null
. ... 然后调用
.getItem("Token")
将返回null
。
I don't know why Firefox behaved differently. 我不知道为什么Firefox的行为有所不同。 From the MDN page on session storage : "Keep in mind that everything you store in any of the storages described in this page is converted to string using its .toString method before being stored."
在会话存储的MDN页面上 : “请记住,存储在此页面中描述的任何存储中的所有内容都将在存储之前使用其.toString方法转换为字符串。”
Your code worked perfectly with me (tested on Chrome). 您的代码非常适合我(已在Chrome上测试)。 However, I suggest you to use the
!
但是,我建议您使用
!
operator and also check the type of the current value: 运算符,并检查当前值的类型:
var a = sessionStorage.getItem("Token");
if(!a && typeof a!=='string'){ //a doesn't exist
//Do something
}else{ //a does exist
//Do something
}
The operator !
操作员
!
will return true
either when a
is null
or undefined
. 当
a
为null
或undefined
时将返回true
。
You could try String(a) == "null"
. 您可以尝试
String(a) == "null"
。 However, if the value of the Token
item is set to "null"
(the string "null"
) the code won't work as expected, so we have to add another condition: 但是,如果
Token
项的值设置为"null"
(字符串"null"
),代码将无法按预期工作,因此我们必须添加另一个条件:
var a = sessionStorage.getItem("Token");
if(String(a)==="null" && typeof a!=="string"){ //a doesn't exist
//Do something
}else{ //a does exist
//Do something
}
This way, the condition will return true when the "stringified" value of a
is "null"
and the type of the a
var is not string
这样一来,当“字符串化”的值的条件将返回true,
a
是"null"
和类型a
变种是不是string
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.