[英]What is the best way to compare a value against 'undefined'?
Is there any differences between 之间有什么区别吗?
var a;
(a == undefined)
(a === undefined)
((typeof a) == "undefined")
((typeof a) === "undefined")
Which one should we use? 我们应该使用哪一个?
Ironically, undefined
can be redefined in JavaScript, not that anyone in their right mind would do that, for example: 具有讽刺意味的是,
undefined
可以在JavaScript中重新定义,而不是任何心智正常的人会这样做,例如:
undefined = "LOL!";
at which point all future equality checks against undefined
will yeild unexpected results! 在这一点上所有未来的
undefined
平等检查都会产生意想不到的结果!
As for the difference between ==
and ===
(the equality operators), == will attempt to coerce values from one type to another, in English that means that 0 == "0"
will evaluate to true even though the types differ (Number vs String) - developers tend to avoid this type of loose equality as it can lead to difficult to debug errors in your code. 至于
==
和===
(相等运算符)之间的差异,==将尝试将值从一种类型强制转换为另一种类型,用英语表示即使类型不同, 0 == "0"
也会评估为真(Number vs String) - 开发人员倾向于避免这种类型的松散相等,因为它可能导致难以在代码中调试错误。
As a result it's safest to use: 因此,最安全的使用方法是:
"undefined" === typeof a
When checking for undefinedness :) 检查undefinedness时:)
I personally like to use 我个人喜欢用
[undefined, null].indexOf(variable) > -1
to check also for null values. 还检查空值。
You should use mentioned above: 你应该使用上面提到的:
"undefined" === typeof a
But if you have lots of variables to check, your code can get ugly at some point, so you may consider to use Java's approach: 但是如果你要检查很多变量,你的代码在某些时候会变得丑陋,所以你可以考虑使用Java的方法:
try { vvv=xxx; zzz=yyyy; mmm=nnn; ooo=ppp; }
catch(err){ alert(err.message); }
Obviously alert() shouldn't be used in a production version, but in debugging version it's very useful. 显然,alert()不应该在生产版本中使用,但在调试版本中它非常有用。 It should work even in old browsers like IE 6:
它甚至应该在IE 6这样的旧浏览器中工作:
https://msdn.microsoft.com/library/4yahc5d8%28v=vs.94%29.aspx https://msdn.microsoft.com/library/4yahc5d8%28v=vs.94%29.aspx
var a;
(a == undefined) //true
(a === undefined) //true
((typeof a) == "undefined") //true
((typeof a) === "undefined") //true
BUT: 但:
var a;
(a == "undefined") //false
(a === "undefined") //false
((typeof a) == undefined) //false
((typeof a) === undefined) //false
If a is undefined, then 如果a未定义,那么
a == undefined
will actually throw an error. 实际上会抛出一个错误。 Use
使用
(typeof a) === "undefined"
Instead. 代替。
If you declare var a
, then it won't be undefined any more - it will be null
instead. 如果声明
var a
,那么它将不再是未定义的 - 它将为null
。 I usually use typeof a == undefined
- and it works fine. 我通常使用
typeof a == undefined
- 它工作正常。 This is especially useful in this situation: 这在这种情况下特别有用:
function myfunc(myvar)
{
if(typeof myvar == "undefined")
{
//the function was called without an argument, simply as myfunc()
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.