解构赋值

概述

目标:数组或者对象
作用:让数组或对象的取值更便捷

数组解构

1
2
3
4
5
6
7
const arr = [11, 22, 33]
// let a = arr[0]
// let b = arr[1]
// let c = arr[2]

let [a, b, c] = arr
console.log(a, b, c)

alt text{: height=75%, width=75%}

1
2
3
4
5
6
const arr = [11, 22, 33]
let [, b, c] = arr
console.log(b, c)

let [a, , d] = arr
console.log(a, d)

alt text{: height=75%, width=75%}

1
2
3
const arr = [1, [2, 3], 4]
let [a, [b, ], d] = arr
console.log(a, b, d)

alt text{: height=75%, width=75%}

对象解构

传统方法:

1
2
3
4
5
6
7
8
9
10
11
const obj = 
{
name: 'ycq',
age: 9,
address: '21234'
}

let a = obj.name
let b = obj.age
let c = obj.address
console.log(a, b, c)

新方法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
const obj = 
{
name: 'ycq',
age: 9,
address: '21234'
}

//这3个变量顺序不影响
let {name, age, address} = obj
console.log(name, age, address)

let {name, age} = obj
console.log(name, age)

let {name, ...rest} = obj
console.log(name, rest)

let {name:unname} = obj
console.log(unname)

alt text{: height=75%, width=75%}