ES6学习之const声明常量的学习
在ES中const关键字用来声明常量,const声明的一经定义不能修改 和let特性差不多,
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
const a = 13; console.log(a); a = 5; //报错
const定义完常量后必须赋值,后面不允许再次赋值
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
const aa; const b; //报错 const定义完后,必须赋值,后面不允许赋值 b=5; alert(b);
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
const c = 12; (function () { console.log(c); //死区 访问不到 const c = 5; //不再同一个作用域 }())
const声明的引用类型(对象)可以追加,但是不可以重新赋值
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
const arr = [1, 2]; // arr=[]; //报错 arr.push(3); //不报错 console.log(arr); const obj = { name: 123, age: 18 }; // obj={}; //报错 obj.name = "小样儿";//不报错 obj.sex = "女"; //不报错 console.log(obj);
如果想定义了不允许修改可以把它冻结 ---》 Object.freeze(需要冻结的参数)
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
const myarr = [1, 2, 3, 4, 5, 6, 7]; Object.freeze(myarr); //冻结起来,冻结之后不能追加也不能修改 myarr.push(8); //报错了
如果是({})对象那么用 obj.xxx=“aaa”;方式不报错,但是不起作用
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
const myobj = Object.freeze({ name: "xiaoyang", age: 18, }); myobj.age = 19; //不报错,但是不起作用 myobj.sex = '女'; //不报错,但是不起作用 console.log(myobj); //输出{name: "xiaoyang", age: 18}