我發生了一些奇怪的事情(至少對我來說),也許有人可以為我詳細說明:
const a = undefined;
const c = {};
/** this works correctly **/
console.log(a === undefined);
/** this does not throw an exception **/
console.log(c.someProperty === undefined);
/** this throws an exception, why? **/
console.log(b === undefined);
只是在上面的示例中,為什么會這樣,如果我想檢查=== undefined未定義的物件屬性,一切都很好,但是一旦我嘗試檢查是否定義了頂級變數,我有錯誤嗎?
這是一個小提琴。
uj5u.com熱心網友回復:
ECMAScript 語言規范宣告訪問不存在的變數會引發ReferenceError(請參閱GetValue),而訪問不存在的屬性會導致undefined(請參閱OrdinaryGet)。
要檢查是否定義了全域變數,可以使用typeof,它不會拋出。
console.log(typeof b === 'undefined');
宣告的頂級變數var也存在于window物件上,因此您也可以使用屬性訪問。
console.log(window.b === undefined);
uj5u.com熱心網友回復:
問題是 b 不是未定義的,它甚至沒有被宣告。你不能呼叫一個沒有宣告的變數,你可以用一個宣告但未定義的變數。
const a = undefined;
const b
const c = {};
console.log(a === undefined) //true
console.log(b === undefined) //true
console.log(c.someProperty === undefined) //true
console.log(typeof d === 'undefined') //true, it does not exist
try{
console.log(d)
} catch (e) {
console.log('error!')
} //error!
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/495973.html
標籤:javascript
