如何将variables与未定义的比较,如果我不知道它们是否存在?

在JavaScript中你可以声明一个variables,如果它是undefined ,你可以检查variable == undefined ; 我知道,但是如何比较一个你不知道的值呢?

例如,我有一个当用户点击一个button时创build的类。 在此之前,课程是不确定的 – 它不存在任何地方; 我怎么能比较呢?

有没有一种方法,而不使用trycatch

最好的方法是检查types ,因为undefined / null / false在JS中是一件棘手的事情。 所以:

 if(typeof obj !== "undefined") { // obj is a valid variable, do something here. } 

请注意, typeof总是返回一个string,如果该variables根本不存在,则不会生成错误。

 if (obj === undefined) { // Create obj } 

如果你正在做广泛的JavaScript编程,你应该习惯使用===和!==当你想做一个types特定的检查。

另外,如果你打算做相当多的javascript,我build议通过JSLint http://www.jslint.com运行代码,起初它可能看起来有些严厉,但是JSLint提醒你的大部分事情最终都会来回来咬你。;

 if (document.getElementById('theElement')) // do whatever after this 

对于引发错误的未定义的事情,testing父对象的属性名称而不是仅仅是variables名 – 所以而不是:

 if (blah) ... 

做:

 if (window.blah) ... 

!undefined在javascript中是真的,所以如果你想知道你的variables或者对象是否是未定义的并且想要采取行动,你可以这样做:

 if(<object or variable>) { //take actions if object is not undefined } else { //take actions if object is undefined } 
 if (!obj) { // object (not class!) doesn't exist yet } else ...