JavaScript检查变量是否存在(定义/初始化) [英] JavaScript check if variable exists (is defined/initialized)
问题描述
检查变量是否已初始化的哪种方法更好/更正?
(假设变量可以包含任何内容(字符串,整数,对象,函数等))
Which method of checking if a variable has been initialized is better/correct? (Assuming the variable could hold anything (string, int, object, function, etc.))
if (elem) { // or !elem
或
if (typeof(elem) !== 'undefined') {
或
if (elem != null) {
推荐答案
typeof
运算符将检查变量是否真的undefined。
The typeof
operator will check if the variable is really undefined.
if (typeof variable === 'undefined') {
// variable is undefined
}
typeof
运算符,与其他运算符在与未声明的变量一起使用时不会抛出 ReferenceError 异常。
The typeof
operator, unlike the other operators, doesn't throw a ReferenceError exception when used with an undeclared variable.
但是,请注意 typeof null
将返回object
。我们必须小心避免将变量初始化为 null
的错误。为了安全起见,这是我们可以使用的:
However, do note that typeof null
will return "object"
. We have to be careful to avoid the mistake of initializing a variable to null
. To be safe, this is what we could use instead:
if (typeof variable === 'undefined' || variable === null) {
// variable is undefined or null
}
有关使用严格比较的更多信息 ===
而不是简单的相等 ==
,请参阅:
在JavaScript比较中应使用哪个等于运算符(== vs ===)?
For more info on using strict comparison ===
instead of simple equality ==
, see:
Which equals operator (== vs ===) should be used in JavaScript comparisons?
这篇关于JavaScript检查变量是否存在(定义/初始化)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!