2016-02-27 59 views
1

如何在JavaScript中創建實用幫助函數來檢查變量的存在以避免錯誤Uncaught ReferenceError: testVar is not definedJavaScript函數檢查是否存在變量以避免錯誤

以下是我正在嘗試做但失敗!

/** 
* Utility Helper Functions 
*/ 
var Utility = { 

    /** 
    * Check if a variable is empty or not 
    * @param mixed value - variable to check if it is empty and exist 
    * @return Boolean - true/false if a variable is empty or not? 
    */ 
    isEmpty: function(value){ 
     //return (value == null || value === ''); 
     return (typeof value === 'undefined' || value === null); 
    }, 
} 

// comment var test out so it will not exist for test 
//var testVar = 'dgfd'; 

// Uncaught ReferenceError: testVar is not defined 
alert(Utility.isEmpty(testVar)); 
+1

之前,你甚至讓你的實用幫手引發錯誤。在PHP中,這將是一個致命的錯誤。你傳遞一個不存在的變量。 – Horen

+0

@霍恩我明白爲什麼它這樣做。我只是認爲在JS中有一種方法可以檢測函數是否存在,除了檢查它是否爲空 – JasonDavis

+0

存在與未定義值存在的變量和不存在的變量之間存在差異。沒有辦法將不存在的變量傳遞給你的函數。 (您可以通過將變量名作爲字符串傳遞並檢查它是否爲'window'的屬性來測試不存在的全局變量,但是您不能爲局部變量執行此操作。) – nnnnnn

回答

2

你不能在isEmpty函數中處理這個,因爲它在進入函數之前拋出錯誤。

您可以使用try/catch,但這會破壞函數的用途。

你可以簡化事情,並刪除整個功能(這也沒必要),像這樣:

if (typeof testVar !== "undefined") { 
    console.log('The variable exists'); 
} 

對象,數組

if(foo instanceof Array) { 

} 
+0

感謝您的解釋。我是JUEST希望儘可能避免每次都使用整個'typeof testVar!==「undefined」'語法,但它似乎不可行 – JasonDavis

+1

@JasonDavis它是如果你使用對象屬性而不是變量 – charlietfl

+2

@JasonDavis:看來實際的問題是你試圖訪問不存在的變量。上下文是什麼?你不應該處於這種情況。 –

相關問題