变量 === 未定义 vs. typeof 变量 === “未定义" [英] variable === undefined vs. typeof variable === "undefined"
问题描述
jQuery Core Style Guidelines 建议了两种不同的检查方式是否定义了变量.
The jQuery Core Style Guidelines suggest two different ways to check whether a variable is defined.
- 全局变量:
typeof variable ===未定义"
- 局部变量:
variable === undefined
- 属性:
object.prop === undefined
为什么 jQuery 对全局变量使用一种方法而对局部变量和属性使用另一种方法?
Why does jQuery use one approach for global variables and another for locals and properties?
推荐答案
对于未声明的变量,typeof foo
将返回字符串字面量 "undefined"
,而身份检查foo === undefined
会触发错误foo is not defined".
For undeclared variables, typeof foo
will return the string literal "undefined"
, whereas the identity check foo === undefined
would trigger the error "foo is not defined".
对于局部变量(您知道已在某处声明),不会发生此类错误,因此需要进行身份检查.
For local variables (which you know are declared somewhere), no such error would occur, hence the identity check.
这篇关于变量 === 未定义 vs. typeof 变量 === “未定义"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!