2015-07-28 55 views
5

如果我有一個未聲明的變量並使用typeof它告訴我它是undefined。 但是,如果我然後使用if (qweasdasd === undefined)檢查它會引發異常。使用typeof vs ===檢查未聲明的變量會產生不同的結果

我不明白這種行爲,因爲如果第一個告訴undefined,那麼第二個檢查應該計算爲if (undefined === undefined),爲什麼它會拋出ReferenceError異常?

+0

無法重現:http://jsfiddle.net/y1xhw9un/ – Jamiec

+0

@Jamiec - 能重現:HTTP:// jsfiddle.net/y1xhw9un/1/ – Quentin

+0

@Quentin - ahh,thats * undeclared *,當它是未定義的,那麼它的工作http://jsfiddle.net/y1xhw9un/2/ – Jamiec

回答

7

typeof看起來像一個函數調用,但它不是 - 它是一個運算符。運營商被允許違反規定。 typeof(qweasdasd)不承擔qweasdasd存在;不管它是否存在,它是什麼typeof存在發現。但是,當您測試qweasdasd === undefined時,您正在使用qweasdasd作爲值,並且當您使用尚未分配值的變量時,JS會投訴。

+0

但是說'qweasdasd'是'undefined'不是騙人的嗎?因爲在我的腦海裏,'if'檢查是完全有效的,應該評估爲'if(undefined === undefined)'。 – damluar

+1

JavaScript在這裏有點令人困惑(並且它不是唯一的地方;不要讓我開始討論'sort'的錯誤)。正如我所說的,未定義的值具有「未定義」是兩種不同的情況,一種不幸的情況是由'typeof(qweasdasd)'和'typeof(undefined)'產生相同的結果而加劇。 – Amadan

+0

有時你只需要放棄理解javascript的邏輯。 – damluar

1

試圖讀取未聲明變量的值(在將該值與undefined的值進行比較之前,您必須先執行此操作)會引發ReferenceError。

typeof運算符應用於未聲明的變量不適用。

+0

爲什麼'typeof'的行爲不同於例如一元'+'(例如'+ foo - > boom!')? –

0

您有一個未定義的變量,但不是未定義的對象值。

console.log(variable) // undefined 
console.log(typeof variable) // "undefined" 
console.log(variable === undefined) // Reference error 
variable = undefined ; 
console.log(variable === undefined) // true 
0

試圖訪問Javascript中的未定義變量給出ReferenceErrortypeof正在工作,因爲它沒有訪問變量值。它檢查它的類型。

typeof不需要定義變量。它的參數應該是一個表達式,它表示要返回類型的對象或原語。

0

typeof是一個運算符,它返回一個字符串,指示未評估操作數的類型。如果未評估的操作數未定義,則無關緊要。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof

>>> if (a !== 'undefined'); 
Exception: ReferenceError: Can't find variable: a 
>>> if (typeof a !== undefined); 
undefined 
>>> if (typeof a !== void 0); 
undefined 
+0

'typeof(parseInt)':''function「'。但'typeof(typeof)':'SyntaxError'。 'typeof'是*不是函數*;如果它*是一個函數,它就會像'parseInt(qweasdasd)'一樣給出'ReferenceError'。 – Amadan

+0

是的,你是對的,我編輯了我的答案。 –

1

我覺得我有這是一個非常簡單的解釋 - 因爲規格這麼說:

  • typeof operator不應該拋出ReferenceError異常,如果變量沒有定義
  1. If Type(val) is Reference, then
    a. If IsUnresolvableReference(val) is true, return "undefined" .
  • === operator應該拋出ReferenceError異常,如果操作數(S)是指不確定的變量
  1. Let lval be GetValue(lref).

[And inside the definition of GetValue we have]

  1. Let base be the result of calling GetBase(V).
  2. If IsUnresolvableReference(V), throw a ReferenceError exception.
相關問題