let obj = {username: 'kobe', age: '18'};
let {username,age} = obj; // 等同于 username=obj.username,age=obj.age
console.log(username, age) // kobe 18
let arr=[1,3,'ad',true]
let [a,b,c,d] = arr;
console.log(a,b) // 1 3
let [,,e,f] = arr;
console.log(e,f) // ad true
let [a,b,...rest] = [1,2,3,4,5,6,7]
console.log(a,b,rest) // 1,2,[3,4,5,6,7]
let arr = [1, 6];
let arr1 = [2, 3, 4, 5]
arr = [1, ...arr1, 6]
console.log(arr) // [1,2,3,4,5,6]
function foo({username,age}) { // {username,age} = obj
console.log(username,age);
}
foo(obj) // kobe 18
function test(...arg) {
arg.forEach(
(value,index) => {
console.log(value)
}
)
}
test(1,2,3,4)
// 输出结果
1,2,3,4
数组解构
{
let a,b;
({a,b} = {a:1,b:2})
console.log(a,b)
}
{
let a,b,c;
[a,b,c = 3] = [1,2];
console.log(a,b,c)
}
输出结果
1 2
1 2 3
实战用途
{
// 交换变量
let a=1;
let b=2;
[a,b]=[b,a]
console.log(a,b)
}
{
function f(){
return [1,2]
}
let a,b;
[a,b]=f()
console.log(a,b)
}
// 输出结果
2 1
1 2
实例分析
let metaData = {
title: 'abc',
test: [{
title: '中国',
desc: '啦啦啦啦啦'
}]
}
let {
title:esTitle,
test:[{title:cnTitle}]
} = metaData;
console.log(esTitle,cnTitle)
// 输出结果
abc 中国