如何在JavaScript中检查未定义的variables
我想检查variables是否被定义。 例如,以下引发一个未定义的错误
alert( x ); 我怎样才能抓住这个错误?
 在JavaScript中, null是一个对象。 对于不存在的东西还有另外一个价值,那就是undefined 。 几乎所有在文档中找不到结构的情况下,DOM都返回null ,但是在JavaScript本身中, undefined是使用的值。 
 其次,不,没有直接的等价物。 如果你真的想检查为null ,做: 
 if (yourvar === null) // Does not execute if yourvar is `undefined` 
 如果你想检查一个variables是否存在,只能用try / catch来完成,因为typeof将会把一个未声明的variables和一个声明为undefined值的variables视为等价。 
 但是,要检查一个variables是否被声明并且不是undefined : 
 if (typeof yourvar !== 'undefined') // Any scope 
如果你知道variables存在,并且想要检查是否存在任何值:
 if (yourvar !== undefined) 
如果你想知道一个成员是否存在独立的,但不在乎它的价值是什么:
 if ('membername' in object) // With inheritance if (object.hasOwnProperty('membername')) // Without inheritance 
如果你想知道一个variables是否真实:
 if (yourvar) 
资源
 真正testingvariables是否是undefined的唯一方法是执行以下操作。 记住,undefined是JavaScript中的一个对象。 
 if (typeof someVar === 'undefined') { // Your variable is undefined } 
在这个线程中的其他一些解决scheme将导致你相信一个variables是未定义的,即使它已被定义(例如值为NULL或0)。
从技术上讲,正确的解决办法是(我相信):
 typeof x === "undefined" 
你有时可以懒惰和使用
 x == null 
但是允许未定义的variablesx和包含null的variablesx返回true。
我经常做:
 function doSomething(variable) { var undef; if(variable === undef) { alert('Hey moron, define this bad boy.'); } } 
一个更简单和更简化的版本将是:
 if (!x) { //Undefined } 
要么
 if (typeof x !== "undefined") { //Do something since x is defined. } 
您也可以使用三元条件运算符:
 var a = "hallo world"; var a = !a ? document.write("i dont know 'a'") : document.write("a = " + a); 
 另一个潜在的“解决scheme”是使用window对象。 它避免了浏览器中的参考错误问题。 
 if (window.x) { alert('x exists and is truthy'); } else { alert('x does not exist, or exists and is falsy'); } 
 我们可以检查undefined如下 
 var x; if (x === undefined) { alert("x is undefined"); } else { alert("x is defined"); } 
我经常用最简单的方法:
 var variable; if (variable === undefined){ console.log('Variable is undefined'); } else { console.log('Variable is defined'); } 
编辑:
没有初始化variables,exception将被抛出“Uncaught ReferenceError:variable is not defined …”
 接受的答案是正确的。 只是想添加一个选项。 你也可以使用try ... catch块来处理这种情况。 一个怪异的例子: 
 var a; try { a = b + 1; // throws ReferenceError if b is not defined } catch (e) { a = 1; // apply some default behavior in case of error } finally { a = a || 0; // normalize the result in any case } 
 注意catch块,这有点麻烦,因为它创build了一个块级作用域。 当然,这个例子是非常简单的,以回答问题,它不包括error handling的最佳实践;)。