const 也用来声明变量,但是声明的是常量,一旦声明,常量值不改变。
<script type="module"> const Pi = 3.1415926535; Pi = 3; console.log(Pi);// error: Pi is read-only </script>
1) const 块级作用域:
<script type="module"> if(true){ const Pi = 3.1415926535; }; console.log(Pi);// error: Pi is not defined </script>
2) const 暂时性死区:
<script type="module"> if(true){ console.log(Pi);//undefined const Pi = 3.1415926535; }; </script>
3) const 不可重复声明:
<script type="module"> { var a = 100; const a = 200; console.log(a);// ERROR: Duplicate declaration, a } </script>
4) const 对象:
<script type="module"> const person = {}; person.name = "zhangsan"; person.age = 30; console.log(person.name); // zhangsan console.log(person.age); // 30 console.log(person); // Object {name: "zhangsan", age: 30} </script>
错误方法:
<script type="module"> const person = {}; person.name = "zhangsan"; person.age = 30; console.log(person.name); // zhangsan console.log(person.age); // 30 console.log(person); // Object {name: "zhangsan", age: 30} person = {}; // Error: person is read-only </script>
5) const 数组:
<script type="module"> const arr = []; console.log(arr); console.log(arr.length);//0 console.log("---------"); arr.push("Hello World!"); console.log(arr); console.log(arr.length);//1 console.log("---------"); arr.length = 0; console.log(arr); console.log(arr.length);//0 console.log("---------"); //错误用法 //arr = ["Hello Everyone!"]; // error: arr is read-only </script>