这两者之间有什么不同吗?
var a;
(a == undefined)
(a === undefined)
((typeof a) == "undefined")
((typeof a) === "undefined")
我们应该使用哪个?
这两者之间有什么不同吗?
var a;
(a == undefined)
(a === undefined)
((typeof a) == "undefined")
((typeof a) === "undefined")
我们应该使用哪个?
具有讽刺意味的是,在JavaScript中undefined
可以被重新定义,虽然没有理智的人会这样做,例如:
undefined = "LOL!";
如果使用undefined
进行未来的相等性检查,将会产生意外的结果!
至于==
和===
(相等运算符)之间的区别,==
会尝试将一个类型的值强制转换为另一个类型,在英语中,这意味着0 == "0"
将被计算为true,即使它们的类型不同(Number vs String) - 开发人员倾向于避免使用这种松散的相等性,因为它可能导致难以调试的错误。
因此,最安全的做法是使用:
"undefined" === typeof a
在检查未定义时 :)
[undefined, null].indexOf(variable) > -1
还要检查空值。
var a;
(a == undefined) //true
(a === undefined) //true
((typeof a) == "undefined") //true
((typeof a) === "undefined") //true
但是:
var a;
(a == "undefined") //false
(a === "undefined") //false
((typeof a) == undefined) //false
((typeof a) === undefined) //false
你应该使用上述提到的内容:
"undefined" === typeof a
但是如果你有很多变量要检查,你的代码可能会变得很丑陋,所以你可以考虑使用Java的方法:
try { vvv=xxx; zzz=yyyy; mmm=nnn; ooo=ppp; }
catch(err){ alert(err.message); }
显然,alert()不应该在生产版本中使用,但在调试版本中非常有用。 它应该能够在旧浏览器(如IE 6)中正常工作:
https://msdn.microsoft.com/library/4yahc5d8%28v=vs.94%29.aspx
a == undefined
会真正抛出一个错误。使用
(typeof a) === "undefined"
相反。
var a
,那么它将不再是未定义的 - 它将变成null
。我通常使用typeof a == undefined
,这非常有效。尤其是在这种情况下,这特别有用:function myfunc(myvar)
{
if(typeof myvar == "undefined")
{
//the function was called without an argument, simply as myfunc()
}
}
typeof
返回一个字符串。 - Shefif
语句会返回 FALSE
-- typeof
函数返回一个字符串值。 - Naftali===
来确定相等性。 - Naftali