[英]ReferenceError when using 'let' to declare variable through a ternary operator
我看過使用三元運算符檢查變量是否已聲明的代碼,如果尚未聲明,則進行聲明。 例如:
var num = (typeof num === 'undefined' ? 1 : num);
console.log(num); //1
但是,這在使用'let'而不是'var'時不起作用:
let num = (typeof num === 'undefined' ? 1 : num); //Uncaught ReferenceError: num is not defined
我知道,與“ var”相比,“ let”具有塊作用域並可以防止重新聲明。 我不確定在上述情況下這將如何導致ReferenceError。 任何人都可以對這里發生的事情有所了解嗎? 謝謝!
您遇到了一種稱為吊裝的事情。
提升影響var
聲明,但不影響let
或const
。
簡而言之,提升將每個var
聲明移動到代碼的頂部。 此代碼的含義:
x = 1;
var y = x + x;
var x;
它被翻譯為:
var y; // y is declared, but undefined (thus y === undefined)
var x; // x is declared, but undefined (thus x === undefined)
x = 1; // x is defined
y = x + x // y is defined
這就是為什么您不會收到錯誤的原因,因為先聲明了x
,然后定義了x
。
但是let
和const
並非如此:
x = 1;
let y = x + x;
let x;
將引發錯誤,因為您在聲明x
之前使用了x
。
編輯
有關詳細信息,請閱讀下面的Felix評論。
不是檢查變量存在的最佳方法。 您不應該通過訪問變量來做到這一點。
如果必須這樣做,請使用:
var barIsDeclared = true;
try{ bar; }
catch(e) {
if(e.name == "ReferenceError") {
barIsDeclared = false;
}
}
如果使用const
和let
變量, const
得到reference error
。 看起來它們在第一個迭代階段沒有被吊起,但這是不正確的 。
無論如何,這就是我測試變量存在的方式,並且沒有問題。
您只是在嘗試對其進行初始化之前對其進行訪問。
let num;
num = (typeof num === 'undefined' ? 1 : num);
console.log(num); //1
這是您想要的實際答案。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.