在 JavaScript 中,let、const 和 var 用於聲明變量,但它們在三個方面有所不同:
1.範圍
2.重新分配
3.吊掛
var 是一個函數作用域,意味著我們在函數內的任何位置訪問 var 變量,如果我們嘗試在函數外部訪問它,它將顯示錯誤 undefined
例:-
function demo(){ if(true){ var n = 3; } console.log(n) } console.log(n) //ReferenceError: n is not defined demo();
let & const 是區塊意味著我們只能在範圍內存取它們,否則會顯示未定義的錯誤
例:-
function demo(){ if(true){ let n = 3; const m = 5; console.log(n) // 3 console.log(m) // 5 } console.log(n) //ReferenceError: n is not defined console.log(m) //ReferenceError: n is not defined } console.log(n) //ReferenceError: n is not defined console.log(m) //ReferenceError: n is not defined demo();
// var example console.log(a); // undefined (due to hoisting) var a = 10; console.log(a); // 10 // let example console.log(b); // ReferenceError: Cannot access 'b' before initialization let b = 20; console.log(b); // 20 // const example const c = 30; c = 40; // TypeError: Assignment to constant variable
免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。
Copyright© 2022 湘ICP备2022001581号-3