ES6中的let和const

1 声明变量的关键字
let a = 1;
const b = 3;
console.log(a,b);//1 3
2 let的用法
  • 块作用域内有效
    全局作用域,函数作用域。另外for循环的,函数的圆括号也是作用域。
for(let i = 0;i < 5;i++){

}
console.log(i);//i is not defined
let x = 5;
function add(x,y=x){
  return x+y;
}
console.log(add(3));//6
  • 变量不提升
console.log(a);//报错:Cannot access 'a' before initialization
let a = 1;
  • 不可重复声明
let a = 1;
let a = 2;//报错:Identifier 'a' has already been declared
3 const的用法

简单用法如下

const PI = 3.14;
console.log(PI);//3.14

const用来声明一个常量,在遵循所有let关键字的法则之外,还需注意:

  • 声明时必须赋值
const PI;
PI = 3.14;
console.log(PI);
//报错:Missing initializer in const declaration 语法不完整,没有在声明时赋值
  • 如果赋值为基本数据类型,那么值为只读,不可变
const PI=3.14;
PI = 3.1415926;
console.log(PI);
//报错:Assignment to constant variable 禁止后续给常量赋值
  • 如果赋值为引用类型值,那么属性可变
const a = {age:18};
a.name = 'zhangsan';
delete a.age;
console.log(a);//{name:'zhangsan'}

ES6总篇--目录

你可能感兴趣的:(ES6中的let和const)