JavaScript 如果 var 存在
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8527957/
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
JavaScript if var exists
提问by Kristian Matthews
I want my code so that if a specific var exists it will perform an action, else it will be ignored and move along. The problem with my code is, if the specific var does not exist it causes an error, presumably ignoring the remainder of the JavaScript code.
我想要我的代码,以便如果存在特定的 var 它将执行一个操作,否则它将被忽略并继续前进。我的代码的问题是,如果特定的 var 不存在,它会导致错误,大概会忽略 JavaScript 代码的其余部分。
Example
例子
var YouTube=EpicKris;
if ((typeof YouTube) != 'undefined' && YouTube != null) {
document.write('YouTube:' + YouTube);
};
采纳答案by Kristian Matthews
Code:
代码:
var YouTube=EpicKris;
if (typeof YouTube!='undefined') {
document.write('YouTube:' + YouTube);
};
Worked out the best method for this, use typeof to check if the var exists. This worked perfectly for me.
为此找出了最好的方法,使用 typeof 来检查 var 是否存在。这对我来说非常有效。
回答by Chango
try {
if(YouTube) {
console.log("exist!");
}
} catch(e) {}
console.log("move one");
Would work when YouTube is not null, undefined, 0 or "".
当 YouTube 不为空、未定义、0 或 "" 时会起作用。
Does that work for you?
那对你有用吗?
回答by Jason Sebring
This is a classic one.
这是一个经典的。
Use the "window" qualifier for cross browser checks on undefined variables and won't break.
使用“window”限定符对未定义的变量进行跨浏览器检查并且不会中断。
if (window.YouTube) { // won't puke
// do your code
}
OR for the hard core sticklers from the peanut gallery...
或者对于花生画廊的铁杆坚持者......
if (this.YouTube) {
// you have to assume you are in the global context though
}
回答by Bhesh Gurung
What about using try/catch
:
怎么样使用try/catch
:
try {
//do stuff
} catch(e) { /* ignore */ }
回答by rafa ble
I believe this is what you may be looking for:
我相信这就是您可能正在寻找的内容:
if (typeof(YouTube)!=='undefined'){
if (YouTube!==undefined && YouTube!==null) {
//do something if variable exists AND is set
}
}
回答by Luan Castro
it's easy... you can do it on 2 ways
这很容易...你可以通过两种方式做到这一点
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
}
or you can be
或者你可以
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
}