如果var存在



我希望我的代码,如果一个特定的var存在,它将执行一个动作,否则它将被忽略并继续前进。我的代码的问题是,如果特定的var不存在,它会导致错误,可能会忽略JavaScript代码的其余部分。

例子
var YouTube=EpicKris;
if ((typeof YouTube) != 'undefined' && YouTube != null) {
    document.write('YouTube:' + YouTube);
};
try {
  if(YouTube) {
    console.log("exist!");
  }
} catch(e) {}
console.log("move one");

当YouTube不是空、未定义、0或"时,

将起作用。

这对你有用吗?

这是一个经典的。

使用"window"限定符来跨浏览器检查未定义的变量,并且不会中断。

if (window.YouTube) { // won't puke
    // do your code
}

或者来自花生画廊的铁杆粉丝…

if (this.YouTube) {
    // you have to assume you are in the global context though 
}

代码:

var YouTube=EpicKris;
if (typeof YouTube!='undefined') {
    document.write('YouTube:' + YouTube);
};

找到了最好的方法,使用typeof来检查var是否存在。

使用try/catch:

try {
    //do stuff
} catch(e) { /* ignore */ }

我相信这就是你要找的:

if (typeof(YouTube)!=='undefined'){
    if (YouTube!==undefined && YouTube!==null) {
        //do something if variable exists AND is set
    }
}

这很容易…有两种方法

var YouTube = window["EpicKris"] ;// or this["EpicKris"] or objectContainer["EpicKris"]
if( YouTube ) { //if is null or undefined (Zero and Empty String too), will be converted to false
    console.log(YouTube);// exists
}else{
    consol.log(YouTube);// null, undefined, 0, "" or false
}

或者

var YouTube = window["EpicKris"] ;// or this["EpicKris"] or objectContainer["EpicKris"]
if( typeof YouTube == "undefined" || YouTube == null ) { //complete test
    console.log(YouTube);//exists
}else{
    console.log(YouTube);//not exists
}

最新更新