如果var存在,则为JavaScript

Kri*_*ews 9 javascript if-statement var exists

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

var YouTube=EpicKris;

if ((typeof YouTube) != 'undefined' && YouTube != null) {
    document.write('YouTube:' + YouTube);
};
Run Code Online (Sandbox Code Playgroud)

Cha*_*ngo 7

try {
  if(YouTube) {
    console.log("exist!");
  }
} catch(e) {}
console.log("move one");
Run Code Online (Sandbox Code Playgroud)

当YouTube不为null,未定义,0或""时可以正常工作.

那对你有用吗?


Jas*_*ing 6

这是一个经典的.

使用"window"限定符对未定义的变量进行跨浏览器检查,不会中断.

if (window.YouTube) { // won't puke
    // do your code
}
Run Code Online (Sandbox Code Playgroud)

或来自花生画廊的硬核粘合剂......

if (this.YouTube) {
    // you have to assume you are in the global context though 
}
Run Code Online (Sandbox Code Playgroud)

  • 如果你在不同的范围内,这将无法奏效.我不建议这样做. (3认同)

Kri*_*ews 3

代码:

var YouTube=EpicKris;

if (typeof YouTube!='undefined') {
    document.write('YouTube:' + YouTube);
};
Run Code Online (Sandbox Code Playgroud)

为此找到了最好的方法,使用 typeof 检查 var 是否存在。这对我来说非常有效。