[英]How to check if a Javascript variable is defined before invoking it
我正在使用Cordova GA插件来跟踪事件,但是当我在浏览器中进行测试时,我会继续:
ReferenceError:未定义插件
我尝试了很多方法来检查插件是否已经定义,但它仍然会抛出此错误。 在调用函数之前,如何正确检查插件是否已定义?
要检查JavaScript变量是否未定义,您可以使用
if (typeof myVariable === 'undefined') {
console.log('The variable is undefined.');
}
您可以在运行代码之前简单地进行检查:
if (window.plugin) {//I had assume that `plugin` is in global scope alert('plugin'); } else { alert('no plugin'); }
使用typeof
if('undefined' === typeof plugin) { alert('no plugin'); } else { alert('plugin ...'); }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.