简体   繁体   English

如何在调用Javascript变量之前检查它是否已定义

[英]How to check if a Javascript variable is defined before invoking it

I am using Cordova GA plugin to track events, but when testing in my browser I keep getting: 我正在使用Cordova GA插件来跟踪事件,但是当我在浏览器中进行测试时,我会继续:

ReferenceError: plugin is not defined ReferenceError:未定义插件

I tried many ways to check if the plugin has been defined, but it still throws this error. 我尝试了很多方法来检查插件是否已经定义,但它仍然会抛出此错误。 How can I properly check if the plugin has been defined before I invoke the function? 在调用函数之前,如何正确检查插件是否已定义?

To check if a JavaScript variable is undefined you can use 要检查JavaScript变量是否未定义,您可以使用

if (typeof myVariable === 'undefined') {
  console.log('The variable is undefined.');
}

You may simply put a check before running your code: 您可以在运行代码之前简单地进行检查:

 if (window.plugin) {//I had assume that `plugin` is in global scope alert('plugin'); } else { alert('no plugin'); } 

Using typeof 使用typeof

 if('undefined' === typeof plugin) { alert('no plugin'); } else { alert('plugin ...'); } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM