在es6中,引入了let和const关键字;
let关键字是用来取代var的;
let作用,与var类似,用于声明一个变量;
特点:
1,在块级作用域里有效(比如循环遍历内部就可以用let定义变量)
实例:
{ let a=0; var b=1; console.log(b); console.log(a); } console.log(b); console.log(a);
报错:ReferenceError: a is not defined
2,不能重复声明
{ let a=0; let a=2; var b=1; var b=2; console.log(b); console.log(a); } console.log(b); console.log(a);
SyntaxError: Identifier 'a' has already been declared
3,不存在变量提升
console.log(a); let a = "apple"; console.log(b); //undefined var b = "banana";
ReferenceError: Cannot access 'a' before initialization
const关键字用来定义常量;
const a=1; a=2;
TypeError: Assignment to constant variable.
const定义的变量,不可改变,其他特性和let一样;