var与let、const的区别
function aoo(){ console.log(a) var a = 1 } aoo(); // 输出 undefined function boo(){ console.log(a) let a = 1 } boo(); // 错误Uncaught ReferenceError: a is not defined
for (var i = 0; i < 2; i++) { console.log(i) } console.log(i) // 输出 2 for (let i = 0; i < 2; i++) { console.log(i) } console.log(i) // 错误Uncaught ReferenceError: a is not defined
var定义的i在全局环境里有效,在for循环外也可以访问,let定义的i只在for循环这个代码块里面有效,在for循环外无法访问,是不存在的。es5没有块级作用域,let是新增的块级作用域(const与let同理)
var a = 1 var a = 2 console.log(a) // 输出 2 let a = 1 let a = 0 console.log(a) // 错误Uncaught SyntaxError: Identifier 'a' has already been declared
var定义的变量可以重复定义,读取最后声明的值,let定义的变量,不可重复定义,会报错已经有变量标识符了(const与let同理)
const a =1 a =2 console.log(a) // 错误Uncaught TypeError: Assignment to constant variable.
const a; //错误Uncaught SyntaxError: Missing initializer in const declaration const是声明常量,声明之后不能修改值,声明的时候必须赋值
es6新增const ,常量声明,常量声明之后无法修改
const a =[] a.push(1) console.log(a) //输出 [1] const a =[] a=[222] console.log(a) //错误Uncaught TypeError: Assignment to constant variable. const aoo = {}; aoo.number = 123; aoo console.log(aoo) //输出{number: 123} const aoo = {}; aoo = {name:'yy'}; console.log(aoo) //错误Uncaught TypeError: Assignment to constant variable.