将值与'undefined'进行比较的最佳方法是什么? [英] What is the best way to compare a value against 'undefined'?

查看:118
本文介绍了将值与'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

检查未定义时:)

这篇关于将值与'undefined'进行比较的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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