Javascript 如何在javascript中处理“未定义”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1984721/
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
How to handle 'undefined' in javascript
提问by Madhu
Possible Duplicate:
Detecting an undefined object property in JavaScript
可能的重复:
在 JavaScript 中检测未定义的对象属性
From the below javascript sample
从下面的javascript示例
try {
if(jsVar) {
proceed();
}
}catch(e){
alert(e);
}
this jsVar is declared and initialized in another file.
这个 jsVar 在另一个文件中声明和初始化。
The problem is that code throws undefined error when this code is executed before the other file (where its declared and initialized) is executed. That is why it is surrounded by try and catch.
问题在于,在执行其他文件(其声明和初始化的位置)之前执行此代码时,代码会引发未定义的错误。这就是为什么它被 try and catch 包围的原因。
What's the best way to handle this undefined error than try catch?
处理这个未定义错误的最佳方法是什么而不是 try catch?
回答by alex.zherdev
You can check the fact with
你可以检查事实
if (typeof(jsVar) == 'undefined') {
...
}
回答by Christoph
As is often the case with JavaScript, there are multiple ways to do this:
与 JavaScript 一样,有多种方法可以做到这一点:
typeof foo !== 'undefined'
window.foo !== undefined
'foo' in window
The first two should be equivalent (as long as fooisn't shadowed by a local variable), whereas the last one will return trueif the global varible is defined, but not initialized (or explicitly set to undefined).
前两个应该是等价的(只要foo不被局部变量遮蔽),而最后一个将true在全局变量已定义但未初始化(或显式设置为undefined)时返回。
回答by Scott
In javascript, the following values will cause the if condition to fail and not execute its statement: null, undefined, false, NaN, the number 0 and the empty string ''.
在 javascript 中,以下值将导致 if 条件失败并且不执行其语句:null、undefined、false、NaN、数字 0 和空字符串 ''。
Assuming that the variable jsVar is a boolean and that we want to call the proceed() method when jsVar is true, we can do the following check.
假设变量 jsVar 是一个布尔值,并且我们想在 jsVar 为真时调用proceed() 方法,我们可以做以下检查。
if (jsVar && jsVar == true)
proceed();
The above code snippet first check that jsVar has been defined and then checks that its value is true. The if condition will be satisfied only if both the conditions are met.
上面的代码片段首先检查 jsVar 是否已定义,然后检查其值是否为真。只有当两个条件都满足时,才会满足 if 条件。
If jsVar is not a boolean then we can substitute the appropriate check in place of jsVar == true in the code above.
如果 jsVar 不是布尔值,那么我们可以用适当的检查代替上面代码中的 jsVar == true 。

