2011-12-15 45 views
9

我想要我的代碼,以便如果存在特定的變量,它將執行一個操作,否則它將被忽略並移動。我的代碼的問題是,如果特定的var不存在,它會導致錯誤,可能會忽略JavaScript代碼的其餘部分。如果var存在,則爲JavaScript

例如,當YouTube是不爲空,未定義,

var YouTube=EpicKris; 

if ((typeof YouTube) != 'undefined' && YouTube != null) { 
    document.write('YouTube:' + YouTube); 
}; 
+0

[在JavaScript中檢測未定義的對象屬性]的可能重複(http://stackoverflow.com/questions/27509/detecting-an-undefined-object-property-in-java腳本) – 2014-04-01 03:44:32

回答

3

代碼:

var YouTube=EpicKris; 

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

摸索出最好的方法這個,使用typeof來檢查var是否存在。這對我來說非常合適。

7
try { 
    if(YouTube) { 
    console.log("exist!"); 
    } 
} catch(e) {} 
console.log("move one"); 

會工作0或 「」。

這是否適合您?

+0

因此,如果var YouTube = EpicKris;不存在或者如果var YouTube = null;或YouTube = 0;那麼不應該發生錯誤,其餘的JavaScript代碼應該運行? – 2011-12-15 23:22:48

+0

Ups,忽略我的答案,是越野車,gurung's更好! – Chango 2011-12-15 23:28:43

+0

好吧,我用古隆的答案來解決它。現在,只要YouTube存在,它就會執行代碼,並且不爲空,0或空字符串。這個答案對你有用嗎? – Chango 2011-12-15 23:34:19

6

這是一個經典之作。

使用「窗口」限定符對未定義的變量進行跨瀏覽器檢查,並且不會中斷。

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

,或從花生畫廊馬虎硬核...

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

怎麼樣使用try/catch

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

我相信這是你可能會尋找:

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

很容易......你可以做到這一點對2種方式

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 

}