ES6 的解构赋值的理解

导读:本篇文章讲解 ES6 的解构赋值的理解,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com

// 解构赋值,即左边的结构和右边的结构一一对应

// 1、数组解构赋值,左边一个数组,右边一个数组,结构一一对应
{
  let a,b;
  [a,b]=[6,8];
  console.log(a,b); // 6  8
}

{
  let a,b,rest;
  [a,b,...rest]=[1,2,3,4,5,6];
  console.log(a,b,rest); // 1  2  [3,4,5,6]
}

//2、对象解构赋值
{
  let a,b;
  ({a,b}={a:6,b:8})
  console.log(a,b); // 6  8
}

{
  let a,b,c;
  [a,b,c=9]=[6,8];
  console.log(a,b,c); // 6  8  9   c 取初值
}

{
    let a,b,c,rest;
    [a,b,c]=[6,8];
    console.log(a,b,c); // 6  8  undifined  c没有成功配对
}

// 3、 适用场景
// 适用于变量交换
{
  let a=6;
  let b=8;
  [a,b]=[b,a];
  console.log(a,b); // 8  6
}

// 方便获取函数的返回值
{
  function f(){
    return [6,8]
  }
  let a,b;
  [a,b]=f();
  console.log(a,b); // 6  8
}

// 再返回多个值得情况下可以选择性的去取值
{
  function f(){
    return [1,2,3,4,5]
  }
  let a,b,c;
  [a,,,b]=f();
  console.log(a,b); // 1 4
}

// 把需要的元素取出,剩余的元素赋给一个数组,需要了再去遍历
{
  function f(){
    return [1,2,3,4,5]
  }
  let a,b,c;
  [a,...b]=f();
    console.log(a,b);// 1  [2 3 4 5]
}
{
    function f(){
        return [1,2,3,4,5]
    }
    let a,b,c;
    [a,,...b]=f();
    console.log(a,b);// 1   [3 4 5]
}

// 4、对象结构赋值
{
  let o={p:66,q:true};
  let {p,q}=o;
  console.log(p,q); // 66  true
}

// 没有赋值取默认值
{
  let {a=10,b=5}={a:3};
  console.log(a,b); // 3  5
}

{
  let aa={
    title:'abc',
    test:[{
      title:'test',
      desc:'abc'
    }]
  }
  let {title:esTitle,test:[{title:cnTitle}]}=aa;
  console.log(esTitle,cnTitle); // abc  test
}

 

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/66477.html

(0)
小半的头像小半

相关推荐

极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!