11/6 解构赋值

52 阅读1分钟

数组解构

//应用场景
    {
        let a = 1;
        let b = 2;
        [a, b] = [b, a];// 变量交换--传统,需要使用中间变量存储
        console.log(a, b);
      }
     {
        function f(){
          return [1, 2, 3];
        }
        let a, b, c;
        [a, b, c] = f();// 传统需要:先接收,用索引解析
        [a, ...b] = f();//不确定函数返回个数,只关心第一个,后面的用数组存储
      }

对象赋值

// 对象解构赋值
      {
        let o={p:42, q:true};
        let {p, q} = o;// 左右得是对象格式
        console.log(p,q);
      }
      {
        let {a=10, b=5} = {a:3};
        console.log(a, b);// 3, 5
      }
      {
        let metaData = {
          title: 'hello',
          test:[{
            title:'test',
            desc:'kiwi'
          }]
        }// 嵌套
        let {title:esTitls, test:[{title:cnTitle}]} = metaData;
        console.log(esTitls, cnTitle);// hello, test
      }

对象赋值

// 字符串结构赋值
      {
        let [a,b,c,d,e] = 'hello';// 将字符串作为一个类似于数组的值进行解构赋
        console.log(a,b,c,d,e);
        let {length} = 'hello';// 对于属性解构赋值,字符串类似于数组的对象,都有一个length属性
        console.log(length);
      }