Javascript 测试是否设置了变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12030078/
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
Javascript testing whether or not a variable is set
提问by Thomas
Generally, I test whether or not a variable is set with something like this:
通常,我测试变量是否设置如下:
if (variable !== '') {
do something...
}
I know there are other methods for testing variables like typeof
but I don't see any advantage - is this an appropriate way to test whether or not a variable is set? Are there problems with it that I should be aware of ?
我知道还有其他测试变量的方法,typeof
但我没有看到任何优势 - 这是测试是否设置变量的合适方法吗?是否存在我应该注意的问题?
回答by Nick
Two reasons:
两个原因:
1) What if the variable is set by getting the contents of an empty input box?
1)如果通过获取空输入框的内容来设置变量怎么办?
if(someScenario){
var variable = $('empty-box').val(); }
Perhaps this is only done in certain cases, like when someScenario
is true. Later on, you want to check if that variable was set. Your means returns false rather than true. Point is, you can come up with scenarios where you get wrong answers.
也许这仅在某些情况下才这样做,例如何时someScenario
为真。稍后,您想检查是否设置了该变量。您的方法返回 false 而不是 true。重点是,你可以想出一些你得到错误答案的场景。
There's just no reason notto do it the accepted way.
没有理由不按照公认的方式去做。
if(typeof variable !== 'undefined')
It's no slower, has no real flaws, and is only a few characters more.
它并不慢,没有真正的缺陷,只是多了几个字符。
2) And most importantly, using typeof
makes it totally clear what you're asking. Readability is crucial, and if another programmer read the first code, they would think you were checking that it wasn't an empty string. The method using typeof
makes it perfectly clear what your conditional is looking for, and reduces the odds of mistakes later on.
2)最重要的是, usingtypeof
使您完全清楚您在问什么。可读性至关重要,如果另一个程序员阅读了第一个代码,他们会认为您在检查它不是空字符串。使用的方法typeof
使您的条件要查找的内容非常清楚,并降低了以后出错的几率。
回答by nnnnnn
If variable
has been declared but might not have a value then your code:
如果variable
已声明但可能没有值,则您的代码:
if (variable !== '') {
tests if it is not the empty string. Is that what you want? An empty string might be a valid value. Better to test for undefined
, or explicitly initialise it to a value that you can then treat as "invalid" (perhaps null
, or whatever suits).
测试它是否不是空字符串。那是你要的吗?空字符串可能是有效值。最好测试undefined
,或明确地将其初始化为一个值,然后您可以将其视为“无效”(也许null
,或任何适合的值)。
If variable
has not been declared at all the above code would result in an errorsuch that execution would stop at that point- you can't test the value of a variable that doesn't exist. So if, for example, you're trying to test a global variable that is created inside a function that may not have been called yet, or perhaps you're using several JS files and one needs to test a variable that may or may not have been created by one of the other files, then the only way to do it is with:
如果variable
完全没有声明,上面的代码将导致错误,以至于执行将在该点停止- 您无法测试不存在的变量的值。因此,例如,如果您正在尝试测试在可能尚未调用的函数中创建的全局变量,或者您可能正在使用多个 JS 文件并且需要测试一个变量,该变量可能会也可能不会已由其他文件之一创建,那么唯一的方法是使用:
if (typeof variable != "undefined") {
回答by Jordan Moncharmont
Check out coffeescript's existential operator, by searching "The Existential Operator" on this page: http://coffeescript.org/
通过在此页面上搜索“The Existential Operator”,查看 coffeescript 的存在运算符:http: //coffeescript.org/
The functional problem with your approach is that is that you may inadvertently assign a blank string to variable at some point prior in your script and your logic block will now do the wrong thing.
您的方法的功能问题在于,您可能会在脚本之前的某个时刻无意中将空字符串分配给变量,并且您的逻辑块现在会做错事。
From a stylistic standpoint your solution is less desirable because your intent to check the existence of the variable is not clear. Someone who was just reading through your code for this the first time might misunderstand what you wrote to mean "I'm expecting there to be a variable named variable set to the blank string" as opposed to "Do something if this variable does not exist."
从文体的角度来看,您的解决方案不太理想,因为您检查变量是否存在的意图不明确。第一次阅读您的代码的人可能会误解您所写的意思是“我希望有一个名为 variable 的变量设置为空白字符串”,而不是“如果此变量不存在,请执行某些操作.”
回答by jeff
Since you're using strict equality testing, the following will all return true:
由于您使用的是严格相等性测试,因此以下内容都将返回 true:
- false
- undefined
- null
- 0
- 错误的
- 不明确的
- 空值
- 0
The only time your check will return false
is when you pass in an empty string.
Is that what you want?
只有false
当您传入一个空字符串时,您的支票才会返回。
那是你要的吗?
回答by Eugen Rieck
This might be highly subjective, but my recommendation is to avoid code, that needs to check, whether a variable is set(a.o.t. has some value or type).
这可能是非常主观的,但我的建议是避免使用需要检查变量是否已设置(aot 具有某些值或类型)的代码。
Consider this snipplet
考虑这个片段
var a=false;
if (some_condition) a="Blah";
if (typeof(a)=='string') ....
if (a===false) ...
this makes sure, a
is always set, while keeping it easily differentiable from ''
, null
or 0
这确保,a
始终设置,同时保持它与''
,null
或0