1.2 const
const 于 let 的共同點不在下面敘述暫時性死區(qū)、不能重復聲明。
const 是用來常量聲明的
const a;
a = 10;
// 報錯 Uncaught SyntaxError: missing initialization in const declaration
const 不能只聲明不賦值。
const a = 20;
a = 10;
// 報錯 // TypeError: Assignment to constant variable.
const 改變常量的值會報錯。
const a = 20;
a = 10;
// 報錯 // TypeError: Assignment to constant variable.
const 存儲常量的空間里面的值不能發(fā)生改變
const a = {};
a.push(20);
a = {};
// TypeError: "a" is read-only
常量 a 儲存的是一個地址,這個地址指向一個對象。不可變的只是這個地址,即不能把 a 指向另一個地址,但對象本身是可變的,所以依然可以為其添加新屬性。
同理數(shù)組也是一樣
const a = [];
a.push(20);
a = [];
// TypeError: "a" is read-only