javascript 检查javascript中是否存在变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16719277/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Checking if a variable exists in javascript
提问by Kirill Ivlev
I know there are two methods to determine if a variable exists and not null(false, empty) in javascript:
我知道在 javascript 中有两种方法可以确定变量是否存在而不是 null(false, empty):
1) if ( typeof variableName !== 'undefined' && variableName )
1) if ( typeof variableName !== 'undefined' && variableName )
2) if ( window.variableName )
2) if ( window.variableName )
which one is more preferred and why?
哪个更受欢迎,为什么?
回答by apsillers
A variable is declaredif accessing the variable name will not produce a ReferenceError
. The expression typeof variableName !== 'undefined'
will be false
in only one of two cases:
一个变量声明,如果访问该变量名称将不会产生ReferenceError
。该表达式typeof variableName !== 'undefined'
将 false
仅适用于以下两种情况之一:
- the variable is not declared (i.e., there is no
var variableName
in scope), or - the variable is declared and its value is
undefined
(i.e., the variable's valueis not defined)
- 变量未声明(即没有
var variableName
作用域),或 - 的变量声明并且其值是
undefined
(即,变量的值是未定义)
Otherwise, the comparison evaluates to true
.
否则,比较结果为true
。
If you really want to test if a variable is declared or not, you'll need to catch
any ReferenceError
produced by attempts to reference it:
如果你真的想测试一个变量是否被声明,你将需要catch
任何ReferenceError
试图引用它的结果:
var barIsDeclared = true;
try{ bar; }
catch(e) {
if(e.name == "ReferenceError") {
barIsDeclared = false;
}
}
If you merely want to test if a declared variable's value is neither undefined
nor null
, you can simply test for it:
如果你只想测试一个声明变量的值是否既不是也不undefined
是null
,你可以简单地测试它:
if (variableName !== undefined && variableName !== null) { ... }
Or equivalently, with a non-strict equality check against null
:
或者等效地,对 进行非严格的平等检查null
:
if (variableName != null) { ... }
Both your second example and your right-hand expression in the &&
operation tests if the value is "falsey", i.e., if it coerces to false
in a boolean context. Such values include null
, false
, 0
, and the empty string, not all of which you may want to discard.
您的第二个示例和您在&&
操作中的右手表达式都测试该值是否为“falsey”,即,它是否false
在布尔上下文中强制转换。此类值包括null
、false
、0
和空字符串,并非您可能希望丢弃所有这些值。
回答by David L
It is important to note that 'undefined' is a perfectly valid value for a variable to hold. If you want to check if the variable exists at all,
重要的是要注意 'undefined' 是一个完全有效的变量值。如果你想检查变量是否存在,
if (window.variableName)
is a more complete check, since it is verifying that the variable has actually been defined. However, this is only useful if the variable is guaranteed to be an object! In addition, as others have pointed out, this could also return false if the value of variableName is false, 0, '', or null.
是一个更完整的检查,因为它正在验证变量是否已实际定义。但是,这仅在变量保证是对象时才有用!此外,正如其他人所指出的,如果 variableName 的值为 false、0、'' 或 null,这也可能返回 false。
That said, that is usually not enough for our everyday purposes, since we often don't want to have an undefined value. As such, you should first check to see that the variable is defined, and then assert that it is not undefined using the typeof operator which, as Adam has pointed out, will not return undefined unless the variable truly is undefined.
也就是说,这对于我们的日常目的来说通常是不够的,因为我们通常不希望有一个未定义的值。因此,您应该首先检查变量是否已定义,然后使用 typeof 运算符断言它不是未定义的,正如 Adam 所指出的,除非变量确实未定义,否则不会返回 undefined。
if ( variableName && typeof variableName !== 'undefined' )
回答by Fizer Khan
If you want to check if a variable (say v) has been defined and is not null:
如果要检查变量(例如 v)是否已定义且不为空:
if (typeof v !== 'undefined' && v !== null) {
// Do some operation
}
If you want to check for all falsy values such as: undefined
, null
, ''
, 0
, false
:
如果要检查所有虚假值,例如:undefined
, null
, ''
, 0
, false
:
if (v) {
// Do some operation
}
回答by Alexander Mihailov
I'm writing an answer only because I do not have enough reputations to comment the accepted answer from apsillers. I agree with his answer, but
我写一个答案只是因为我没有足够的声誉来评论apsillers接受的答案。我同意他的回答,但是
If you really want to test if a variable is undeclared, you'll need to catch the ReferenceError ...
如果您真的想测试变量是否未声明,则需要捕获 ReferenceError ...
is not the only way. One can do just:
不是唯一的方法。一个人可以这样做:
this.hasOwnProperty("bar")
to check if there is a variable bardeclared in the current context. (I'm not sure, but calling the hasOwnPropertycould also be more fast/effective than raising an exception) This works only for the current context (not for the whole current scope).
检查当前上下文中是否声明了变量bar。(我不确定,但调用hasOwnProperty也可能比引发异常更快/更有效)这仅适用于当前上下文(不适用于整个当前范围)。
回答by Pika
if ( typeof variableName !== 'undefined' && variableName )
//// could throw an error if var doesnt exist at all
if ( window.variableName )
//// could be true if var == 0
////further on it depends on what is stored into that var
// if you expect an object to be stored in that var maybe
if ( !!window.variableName )
//could be the right way
best way => see what works for your case
回答by Jonas Tomanga
I found this shorter and much better:
我发现这更短,更好:
if(varName !== (undefined || null)) { //do something }
回答by Guanxi
if (variable)
can be used if variable is guaranteed to be an object, or if false, 0, etc. are considered "default" values (hence equivalent to undefined or null).
if (variable)
如果变量被保证是一个对象,或者如果 false、0 等被认为是“默认”值(因此等效于 undefined 或 null),则可以使用它。
typeof variable == 'undefined'
can be used in cases where a specified null has a distinct meaning to an uninitialised variable or property. This check will not throw and error is variable is not declared.
typeof variable == 'undefined'
可用于指定的 null 对未初始化的变量或属性具有不同含义的情况。此检查不会抛出并且错误是未声明变量。