Skip to content

解构赋值

1.理解:

是一种快速从对象或数组中取出成员的一种语法

2.步骤:

  1. 解构
  2. 赋值

3.解构数组:

1.对于数组的解构,通过[]实现

声明一个中括号 其实就是一个数组集合,中括号中的每个值就是变量,依次接收 赋值的数组的值

js
let arr1 = ['hello',true,231,'world',false];
console.log(arr1);
   

let [aa,bb,cc,dd,ee] = arr1;
console.log(aa);  // 'hello'
console.log(bb);  // true
console.log(cc);  // 231
console.log(dd);  // 'world'
console.log(ee);  // false

2.如果 中括号中 声明的变量数量小于赋值数组的值的个数,则依次进行接收,数组后面的值就没有变量接收

js
let arr1 = ['hello',true,231,'world',false];

let [a1,b1,c1] = arr1;
console.log(a1);  // 'hello'
console.log(b1);  // true
console.log(c1);  // 231

3.如果 中括号中 声明的变量数量 大于 赋值数组的值的个数,则 后面的变量不会接收到值,值为undefined

js
let arr1 = ['hello',true,231,'world',false];

let [a2,b2,c2,d2,e2,f2,g2] = arr1;
console.log(a2);  // 'hello'
console.log(b2);  // true
console.log(c2);  // 231
console.log(d2);  // 'world'
console.log(e2);  // false

console.log(f2);  // undefined
console.log(g2);  // undefined

4.在 解构的过程中 可以给解构的变量赋值,这个值是默认值

  • 如果 赋值的数组 中 对应c项 有值,则按照数组对应项的值赋值给变量

  • 如果 赋值的数组 中 对应项 没有值,则按照给变量的默认值赋值

js
let arr2 = [11,22,,33];
console.log(arr2);

let [q=1,w=2,o=3,r=4,t=5,y=6] = arr2;
console.log(q);  // 11
console.log(w);  // 22
console.log(o);  // 3
console.log(r);  // 33
console.log(t);  // 5
console.log(y);  // 6

5.可以 实现对 字符串的 解构,语法方法和数组的解构是一样的

js
let str1 = 'hel lo!!!';
let [aaa,bbb,ccc,ddd,eee,fff,ggg,hhh,iii] = str1;
console.log(aaa,bbb,ccc,ddd,eee,fff,ggg,hhh,iii);	// hel lo!!!

4.解构对象

对于 对象的解构 通过 { } 实现

花括号中的变量 需要使用 对象的key(键)

js
let obj = {
    name: '好的',
    age: 18,
    sex: '男',
    hello: function(){
        alert('我好帅')
    }
}

// 花括号中的变量 需要使用 对象的key(键) 实现
let {name,age,sex,hello} = obj;
console.log(name);  // '好的'
console.log(hello);  // ƒ (){alert('我好帅')}

//相较于数据解构,对象结构不需要按照顺序
let {hello} = obj;
hello();


// 传统的访问对象成员
let haha = obj.age;
console.log(haha);  // 18

MIT Licensed