let var const
1. var 可声明前置
a = 3
var a
var a = 4
2. let不可声明前置
a = 3 //报错
let a
3. let不可重复声明
let a = 3
let a = 4 //报错
var a = 5 //报错
#### 4. 存在块级作用域
for(let i =0; i<3; i++){
console.log(i)
}
console.log(i) //报错
IIFE的替换
(function(){
var a = 1
}())
{
let a = 1
}
暂时性死区(TDZ):在let声明变量之前都是该变量的死区,在死区内该变量不可使用
5. const 声明的常量不可改变
const a = 1
a = 2 //报错
const obj = {a: 1}
obj.a = 2 //没问题
obj = {a: 2} //报错
6. 适用于let的同样适用于const
解构赋值
1. 数组的解构
let [a,b,c] = [1,2,3]
console.log(a, b, c)
let [a, [b], c] = [2, [3], 4]
a //2
b //3
c //4
let [a] = 1 //报错
2. 默认值
let [a, b = 2] = [3]
a // 3
b // 2
let [a, b = 2] = [3, 4]
a //3
b //4
数组对应对值有没有?如果没有(数组对没有指undefined)就使用默认值,如果有就使用对应值
let [a=2, b=3] = [undefined, null]
a //2
b //null
let [a=1, b=a] = [2]
a //2
b //2
3. 对象的解构赋值
前置知识
let [name, age] = ['hunger', 3]
let p1 = {name, age}
//等同于
let p2 = {name: name, age: age}
解构范例
let {name, age} = {name: 'jirengu', age: 4}
name //‘jirengu’
age //4
以上代码等同于
let name
let age
({name: name, age: age} = {name: 'jirengu', age: 4})
4. 默认值
let {x, y=5} = {x: 1}
x //1
y //5
5. 函数解构
function add([x=1, y=2]){
return x+y
}
add() //Error
add([2]) //4
add([3,4]) //7
function sum({x, y}={x:0, y:0}, {a=1, b=1}){
return [x+a, y+b]
}
sum({x:1, y:2}, {a:2}) //[3, 3]
6. 作用
let [x, y] = [1, 2];
[x, y] = [y, x]
x //2
y // 1
function ajax({url, type=‘GET’}){
}
ajax({url: ‘http://localhost:3000/getData’})