• ES6 解构赋值--一般用法


     

    解构(Destructuring):ES6 允许按照一定模式,从数组和对象中提取值,对变量进行赋值。

    1. <script>
    2. let a = 1;
    3. let b = 2;
    4. let c = 3;
    5. script>

    等价于: 可以从数组中提取值,按照对应位置,对变量赋值。==只要左右两边相等,就会赋值,如果解构不成功,变量的值就等于undefined

    1. <script>
    2. //等价于
    3. let [a,b,c]=[1,2,3]
    4. script>
    1. <script>
    2. let [ , , third] = ["foo", "bar", "baz"];
    3. console.log(third)
    4. script>

    0、 只要等号两边的模式相同,左边的变量就会被赋予对应的值。

    1. <script>
    2. let [head, ...tail] = [1, 2, 3, 4];
    3. console.log(head)// 1
    4. console.log(tail)// [2, 3, 4]
    5. script>

    1、如果解构不成功,变量的值就等于undefined 

    1. <script>
    2. let [x, y, ...z] = ['a'];
    3. console.log (x) // "a"
    4. console.log(y) // undefined
    5. console.log(z) // []
    6. script>

    2、不完全解构,即等号左边的模式,只匹配一部分的等号右边的数组。这种情况下,解构依然可以成功。——两个情况

    1. <script>
    2. let [x, y] = [1, 2, 3];
    3. console.log (x) //1
    4. console.log(y) //2
    5. script>
    1. <script>
    2. let [x, [y], z] = [1, [2, 3], 4];
    3. console.log (x) //1
    4. console.log(y) //2
    5. console.log(z)//4
    6. script>

    3、如果等号的右边不是数组(是不是可遍历的结构),那么将会报错。

    1. <script>
    2. // 报错--全部-每一句
    3. let [foo] = 1;
    4. // let [foo] = false;
    5. // let [foo] = NaN;
    6. // let [foo] = undefined;
    7. // let [foo] = null;
    8. // let [foo] = {};
    9. script>

    等号右边的值(false,NaN,undefined,null)赋值转化为对象不具备Iterator 接口,对象本身不具备Iterator 接口

  • 相关阅读:
    【Node.js】Express-Generator:快速生成Express应用程序的利器
    shell编程基础(第14篇:管道符号的妙用)
    《痞子衡嵌入式半月刊》 第 94 期
    细说react源码中的合成事件
    Git基本概念
    Verilog实现定点乘法器
    【前端方案】-表格排序列LRU缓存方案
    Spring和Netty整合详解
    使用nsenter调试k8s网络
    Linux安装Net7SDK运行Net项目
  • 原文地址:https://blog.csdn.net/weixin_47295886/article/details/127047683