var
用var申明一个变量:
var a = 1;console.log(a) // 1
console.log(a) // undefinedvar a = 1;
js的申明过程:
var a; // undefined,只申明,不赋值。会有个默认值undefineda = 1 // 1
例子:
var a = 1;var a;console.log(a) // 1, 对重复定义且未赋值的变量,不会覆盖之前的值
var a = 1;var a = 2;console.log(a) // 2, 重复定义有赋值,覆盖之前的值
注:没有修饰符的变量,为全局变量,如:a = 3
,这里a为全局变量
let
let没有与解析,不能先用再申明
console.log(a); // 报错:a is not definedlet a = 2;
同一个作用域下不能重复申明,具有块及作用域
let a = 1;let a = 3;console.log(a); // 报错:Identifier 'a' has already been declared
let a = 1;{let a = 2;console.log(a) // 2(不在同一个作用域)}
const
同let,另外const申明后不可修改,对象除外
const a = 1;a = 2;console.log(a) // 报错:Assignment to constant variable
const a = {name: 'lyh',age: 18}a.name = 'lyh2'console.log(a) // {name: 'lyh2', age: 18}
const a = [1,2]a[1] = 5console.log(a)