如果我有一個未聲明的變量並使用typeof
它告訴我它是undefined
。 但是,如果我然後使用if (qweasdasd === undefined)
檢查它會引發異常。使用typeof vs ===檢查未聲明的變量會產生不同的結果
我不明白這種行爲,因爲如果第一個告訴undefined
,那麼第二個檢查應該計算爲if (undefined === undefined)
,爲什麼它會拋出ReferenceError異常?
如果我有一個未聲明的變量並使用typeof
它告訴我它是undefined
。 但是,如果我然後使用if (qweasdasd === undefined)
檢查它會引發異常。使用typeof vs ===檢查未聲明的變量會產生不同的結果
我不明白這種行爲,因爲如果第一個告訴undefined
,那麼第二個檢查應該計算爲if (undefined === undefined)
,爲什麼它會拋出ReferenceError異常?
typeof
看起來像一個函數調用,但它不是 - 它是一個運算符。運營商被允許違反規定。 typeof(qweasdasd)
不承擔qweasdasd
存在;不管它是否存在,它是什麼typeof
存在發現。但是,當您測試qweasdasd === undefined
時,您正在使用qweasdasd
作爲值,並且當您使用尚未分配值的變量時,JS會投訴。
試圖讀取未聲明變量的值(在將該值與undefined
的值進行比較之前,您必須先執行此操作)會引發ReferenceError。
將typeof
運算符應用於未聲明的變量不適用。
爲什麼'typeof'的行爲不同於例如一元'+'(例如'+ foo - > boom!')? –
您有一個未定義的變量,但不是未定義的對象值。
console.log(variable) // undefined
console.log(typeof variable) // "undefined"
console.log(variable === undefined) // Reference error
variable = undefined ;
console.log(variable === undefined) // true
試圖訪問Javascript中的未定義變量給出ReferenceError
。 typeof
正在工作,因爲它沒有訪問變量值。它檢查它的類型。
typeof不需要定義變量。它的參數應該是一個表達式,它表示要返回類型的對象或原語。
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
'typeof(parseInt)':''function「'。但'typeof(typeof)':'SyntaxError'。 'typeof'是*不是函數*;如果它*是一個函數,它就會像'parseInt(qweasdasd)'一樣給出'ReferenceError'。 – Amadan
是的,你是對的,我編輯了我的答案。 –
我覺得我有這是一個非常簡單的解釋 - 因爲規格這麼說:
typeof
operator不應該拋出ReferenceError異常,如果變量沒有定義
- If Type(val) is Reference, then
a. If IsUnresolvableReference(val) is true, return"undefined"
.
===
operator應該拋出ReferenceError異常,如果操作數(S)是指不確定的變量
- Let lval be GetValue(lref).
[And inside the definition of GetValue we have]
- Let base be the result of calling GetBase(V).
- If IsUnresolvableReference(V), throw a ReferenceError exception.
無法重現:http://jsfiddle.net/y1xhw9un/ – Jamiec
@Jamiec - 能重現:HTTP:// jsfiddle.net/y1xhw9un/1/ – Quentin
@Quentin - ahh,thats * undeclared *,當它是未定義的,那麼它的工作http://jsfiddle.net/y1xhw9un/2/ – Jamiec