簡體   English   中英

使用“ let”通過三元運算符聲明變量時出現ReferenceError

[英]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聲明,但不影響letconst

簡而言之,提升將每個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

但是letconst並非如此:

x = 1;
let y = x + x;
let x;

將引發錯誤,因為您在聲明x之前使用了x

編輯

有關詳細信息,請閱讀下面的Felix評論。

不是檢查變量存在的最佳方法。 您不應該通過訪問變量來做到這一點。

如果必須這樣做,請使用:

var barIsDeclared = true; 
try{ bar; }
catch(e) {
    if(e.name == "ReferenceError") {
        barIsDeclared = false;
    }
}

如果使用constlet變量, const得到reference error 看起來它們在第一個迭代階段沒有被吊起,但這是不正確的

無論如何,這就是我測試變量存在的方式,並且沒有問題。

您只是在嘗試對其進行初始化之前對其進行訪問。

let num;
num = (typeof num === 'undefined' ? 1 : num);
console.log(num); //1

這是您想要的實際答案。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM