1.2 const
const 于 let 的共同点不在下面叙述暂时性死区、不能重复声明。
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
存储常量的空间里面的值不能发生改变
const a = {};
a.push(20);
a = {};
// TypeError: "a" is read-only
常量 a 储存的是一个地址,这个地址指向一个对象。不可变的只是这个地址,即不能把 a 指向另一个地址,但对象本身是可变的,所以依然可以为其添加新属性。
同理数组也是一样
const a = [];
a.push(20);
a = [];
// TypeError: "a" is read-only
网友评论