1、解构表达式传参
let User = {
name : 'ghostwu',
age : 22
};
function show( obj ){
console.log( obj ); //obj其实就是User对象
console.log( obj === User ); //true
//函数中可以访问在参数中解构出来的变量
console.log( name, age ); //ghostwu, 22
}
show( { name, age } = User ); //表达式传值,整个表达式的值 取决于右边,所以把User传给了obj
console.log( name, age ); //ghostwu, 22
2、解构数组
let arr = [ 10, 20, 30, 40 ];
// 数组用[]解构
let [ one, two ] = arr;
console.log( one, two ); //10 20
3、解构嵌套数组
let arr = [ 10, [ 20, 30 ], 40 ];
console.log( arr[1][1] ); //30
let [ one, two, three, four ] = arr;
console.log( one, two, three, four ); //10 [20, 30] 40 undefined
[one, [ two, three ], four ] = arr; //前面不要let,否则会报重定义错误
console.log( one, two, three, four ); //10 20 30 40
4、解构中的不定参数(...)
let arr = [ 10, 20, 30 ];
let [ one, ...others ] = arr;
console.log( others.length ); //2
console.log( one ); //10
console.log( others[0] ); //20
console.log( others[1] ); //30
5、嵌套对象解构
let User = {
name : 'ghostwu',
age : 22,
class : {
group1 : {
one : '王超',
two : '马汉'
},
group2 : {
one : '张龙',
two : '赵虎'
}
}
};
//在User对象解构class, 在class中解构group1
let { class : { group1 } } = User;
console.log( group1.one ); //王超
console.log( group1.two ); //马汉
//在User对象解构class, 在class中解构group1, 在group1中解构one, two
({ class : { group1 : { one, two } } } = User);
console.log( one, two ); //王超, 马汉
//重命名group1 为 diyizu
({ class : { group1 : diyizu } } = User);
console.log( diyizu.one ); //王超
console.log( diyizu.two ); //马汉
//three 赋默认值
({ class : { group1 : { one, two, three = '展昭' } } } = User);
console.log( one, two, three );//王超,马汉,展昭