变量
let num = 123
const str = '123'
console.log(num, str)
解构赋值
{
let a, b, c
[a, b, c = 3] = [1, 2]
// 1 2 3
console.log(a, b, c)
}
{
let a, b, arr
[a, b, ...arr] = [1, 2, 4, 5, 6, 7, 8, 9]
// 1 2
console.log(a, b)
// [4, 5, 6, 7, 8, 9]
console.log(arr)
}
{
let a, b
({a, b} = {a: 1, b: 2})
// 1 2
console.log(a, b)
}
{
let a = 1
let b = 2;
// 变量交换
[a, b] = [b, a]
console.log(a, b)
}
数组解构
test () {
return [1, 2]
}
let a, b
[a, b] = this.test()
// 1 2
console.log(a, b)
只取需要的值
test () {
return [1, 2, 3, 4, 5]
}
let a, b
[a, , , b] = this.test()
// 1 4
console.log(a, b)
let a, b
[a, ...b] = this.test()
// 1 [2, 3, 4, 5]
console.log(a, b)
let a, b
[a, , ...b] = this.test()
// 1 [3, 4, 5]
console.log(a, b)
对象解构
let a = {name: 'ronle', index: 1}
let {name, index} = a
// ronle 1
console.log(name, index)
let a = {user: 'ronle', num: 1}
// 变量重命名
let {user: name, num: index} = a
console.log(name, index)
let {a = 10, b = 5} = {a: 3}
// 3 5
console.log(a, b)
let metaDate = {
title: 'hello',
test: [
{
name: 'ronle',
desc: 'desc'
}
]
}
let {title: esTitle, test: [{name: cnName}]} = metaDate
// hello ronle
console.log(esTitle, cnName)