2011-12-16 101 views
6

我一直以爲我可以通過比較不確定的檢查未定義的變種,但是這是我在Chrome控制檯出現錯誤:如何檢查變量或對象是否未定義?

enter image description here

如何如何檢查爲對象的jQuery是未定義?

編輯:

enter image description here

如果(jQuery的)是給我的問題太

編輯:

解決方案:

if(window.jQuery)作品。 typeof(jQuery) == 'undefined'也可以。

任何人都可以解釋爲什麼?

+0

[http://stackoverflow.com/questions/8531059/how-to-check-if-a-variable-or-object-is-undefined/8531076#8531076][1] [1]:http://stackoverflow.com/questions/8531059/how-to-check-if-a-variable-or-object-is-undefined/8531076#8531076 – 2011-12-16 07:40:22

+0

HTTP:// stackoverflow.com/questions/27509/detecting-an-undefined-object-property-in-javascript,http://stackoverflow.com/questions/8531059/how-to-check-if-a-variable-or-object- is-undefined – 2011-12-16 07:49:47

回答

9

有幾種解決方案:

  1. 使用typeof。這是一個特殊的操作員,絕不會導致ReferenceError。對於在上下文中不存在的變量,其值undefined的評估爲「未定義」。我不是它的粉絲,但它似乎很常見。使用。這會強制執行「屬性查找」:屬性查找永不失敗,如果該屬性不存在,則返回undefined。我已經看到它在一些框架中使用。假設背景有缺點(通常爲window)。

  2. 確保該變量爲「聲明」:var jQuery; if (jQuery) { /* yay */ }。似乎並不常見,但它完全有效。請注意,var只是一個註釋並已懸掛。在全球範圍內,這將創建「jQuery」屬性。

  3. 趕上ReferenceError。老實說,我從來沒有見過這個,也不推薦它,但它會工作。

快樂編碼。

2

據我知道你能行

if(typeof X == 'undefined') 

但也有資源,你可能想看看裝載機。我面前的答案也是正確的。

-1

if(jQuery)應該夠了,不是嗎?

+0

不會。它可能會拋出一個ReferenceError(上面的內容在帖子中)。 – 2011-12-16 07:26:55

3

here

if(typeof jQuery == "undefined") { 
    document.write("undefined"); 
}else{ 
    document.write("Exists"); 
} 
+0

雖然這個「作弊」與`var test = 1`,因爲上下文是不一樣的:)但它仍然是有效的這種情況沒有它,但。 – 2011-12-16 08:01:06

5

流程1:

if (jQuery) { 
    // jQuery is loaded 
} else { 
    // jQuery is not loaded 
} 

流程2:

if (typeof jQuery == 'undefined') { 
    // jQuery is not loaded 
} else { 
    // jQuery is loaded 
} 
1

在你的代碼名爲 「jQuery的」 變量從未宣佈,所以它會拋出一個錯誤,如「xxx(變量名稱)未定義」。

可以使用typeof運算符來檢查是一個變量未定義或不

if (typeof(jQuery) == "undefined")