我對代碼的假設是第二個let x
上面的代碼位於時間死區。因此不應該拋出錯誤。瞭解設定範圍
代碼
function f(condition, x) {
if (condition) {
let x = 100;
return x;
}
let x = 30; // <---- throw error
return x;
}
f(true, 1);
我對代碼的假設是第二個let x
上面的代碼位於時間死區。因此不應該拋出錯誤。瞭解設定範圍
代碼
function f(condition, x) {
if (condition) {
let x = 100;
return x;
}
let x = 30; // <---- throw error
return x;
}
f(true, 1);
那麼這裏的問題是,你重新聲明同一變量x
兩次在同一function
,所以變量x
將被吊起。
if (condition) {
//This x declaration is fine as it wasn't preceded with any others declaration inside the same block scope
let x = 100;
return x;
}
//Now this second x declaration will cause the hoisting problem
let x = 30; // <---- throw error
這裏第二let x = 30;
聲明衝頂您function
範圍x
變量。所以得出的結論是,你不能在同一個範圍內多次聲明同一個變量。
有關在Javascript varaible提升進一步的閱讀,您可以檢查:
問題似乎是與X已經是具有相同的範圍,因爲外X一個函數參數。如果我更改功能參數x與y,代碼工作正常。
代碼
function f(condition, y) {
if (condition) {
let x = 100;
return x;
}
let x = 30; // <---- doesnt throw error
return x;
}
f(true, 1);
'let'是 「塊作用域」 - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/發言/讓 –
我知道讓是塊範圍 – aWebDeveloper
閱讀關於在Javascript中提升,所以你可以瞭解哪些代碼的例子失敗。 – Dez