解构赋值
概述
目标:数组或者对象
作用:让数组或对象的取值更便捷
数组解构
1 2 3 4 5 6 7
| const arr = [11, 22, 33]
let [a, b, c] = arr console.log(a, b, c)
|
{: 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)
|
{: height=75%, width=75%}
1 2 3
| const arr = [1, [2, 3], 4] let [a, [b, ], d] = arr console.log(a, b, d)
|
{: 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' }
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)
|
{: height=75%, width=75%}