[英]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.