一、基本用法
const命令是用来声明一个只读的常量,这个值不会变。
const声明常量与let一样,不可重复声明。
二、本质(我困惑的地方)
const实际上保证的并不是变量的值不可以改动,而是变量指向的内存地址不可改动。
对于简单类型的数据,比如数值、字符串、布尔等,值就保存在变量指向的内存地址中,因此等于常量。但是对于复合类型数据,比如对象和数组,变量指向的内存地址保存的是一个指针,const只保证指针是固定的,对于它指向的数据结构是不能变的。
所以,conse如果定义一个常量,定以后就不能变的,如果是引用类型,那么就能改变它的属性。
const foo={}; foo.pro=123;
console.log(foo.pro);//123
//以下也不会报错
const arr=[];
arr.push("hi~");
最后,ES5只有var命令和function命令两种方式来声明变量。ES6扩展了let、const、import和class四种方法。