js解构赋值详解。

解构赋值:

混合式赋值,我们称之为解构赋值。
解构赋值中,等号右侧是一个数组或对象,指定左侧一个或多个变量的语法。
语法保持格式一致。

let [x,y] = [1,2];   // 等价 x=1 y=2
[x,y] = [x+1,y+2];  //  等价 x = x+1,y+2
[x,y] = [y,x];  // 交换两个变量的值

右侧的数组包含的元素不必和左侧的变量一一对应。左侧多余的变量视为undefined,
右侧多余的值则忽略。左侧的变量可以用逗号跳过右侧对应的值

let [x,y] = [1]; // x=1 y=undefined // 左侧多余变量视为undefined
[x,y] = [1,2,3]; // x = 1  y = 2    右侧多余的值忽略
[,x,y] = [1,2,3]; // x=2  y = 3 逗号跳过了1

链式解构赋值:

let first,second,all;
all = [first,second] = [1,2,3,4]; // frist=1  second=2 all=[1,2,3,4]

解构赋值可以嵌套:

let [one,[twoA,twoB]] = [1,[2,3]];  //  one=1 twoA=2 twoB=3

解构赋值还可以解构数据结构:

let data = {
  name:'李四',
  age:'20',
  person:[
   weight:'120',
   height:'1米8'
]
}
let ({name:a,age:b,person:[{weight:c,height:d}]} = data);
console.log(a); // 20
console.log(weight); //120

猜你喜欢

转载自blog.csdn.net/weixin_44164824/article/details/89040409
今日推荐