将值与'undefined'进行比较的最佳方法是什么?

问题描述:

var a;
(a == undefined)
(a === undefined)
((typeof a) == "undefined")
((typeof a) === "undefined")

我们应该使用哪一个?

具有讽刺意味的是, undefined 可以在JavaScript中重新定义,而不是那些心智正常的人会这样做,例如:

Ironically, undefined can be redefined in JavaScript, not that anyone in their right mind would do that, for example:

undefined = "LOL!";

此时所有未来的等式检查 undefined 会产生意想不到的结果!

at which point all future equality checks against undefined will yeild unexpected results!

至于 == 之间的差异== = (相等运算符),==将尝试将值从一种类型强制转换为另一种类型,用英语表示 0 ==0即使类型不同(Number vs String),它也会评估为true - 开发人员倾向于避免这种类型的松散相等,因为它可能导致代码中的调试错误。

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.

因此最安全:

"undefined" === typeof a

检查未定义时:)