zoukankan      html  css  js  c++  java
  • ES6 解构赋值

    一、数组的解构赋值

          // 基本赋值
          let [a,b,c]=["q","w","e"];
          console.log(a,b,c);//q w e
    
          // 嵌套结构
          let [fruits,[apple,banana,pear],vegetables]=["水果",["苹果","香蕉","梨"],"蔬菜"];
          console.log(fruits,apple,banana,pear,vegetables);//水果 苹果 香蕉 梨 蔬菜
    
          // 左侧缺少变量
          let [app,,str]=["o","p","q"];
          console.log(app,str);//o q
    
          // 有默认值的情况
          let [n=1,u,m]=[,9,0];
          console.log(n,u,m);//1 9 0

    从上面几个例子可以看出,只要等号的左边和右边的形式一样,左边的变量就会被赋予右边对应的值。如果左边变量有默认值,右边对应位置为空,则使用默认值,否则使用右边的值。

    若左侧缺少变量,右侧多余的值则会被忽略,这种情况就为不完全解构。

          // 数组的拼接
          let per = ["j", "x", "f"];
          let after = ["p", "i", "g"];
          let allArr = [...per, ...after];
          console.log(allArr); // ["j", "x", "f", "p", "i", "g"]
    
          // 右侧为字符串形式
          let [i, o, v, w, z] = "water";
          console.log(i, o, v, w, z); //w a t e r

    如果想进行数组的拼接,可以使用扩展运算符(‘...’)进行解构赋值;

    如果解构的对象是一个可遍历的对象,那么等号左侧对应的变量会被赋予右侧对应的值。

          //左侧变量多于右侧的值
          let [h,d]=[1];
          console.log(h,d);// 1 undefined

    上面的这种情况,左侧的变量d没有对应的值,为undefined,解构不成功。

    二、对象的解构赋值

          // 基本
          let { a, b, c } = { a: "q", b: "w", c: "e" };
          console.log(a, b, c);
    
          // 嵌套结构
          let obj = { p: ["red", { y: "apple" }] };
          let {
            p: [future, { y: content }]
          } = obj;
    
          // 对象的添加
          let add = { apple: "苹果", pear: "梨", banana: "香蕉" };
          let { kinds, apple, pear, banana } = { kinds: "种类", ...add };
          console.log(kinds, apple, pear, banana);
    
          //先声明变量,再进行解构赋值时,需要加上圆括号
          let x;
          ({ x } = { x: 125 });

    对象的解构赋值和数组的不同之处就在于对象是无序的,所以,对象是根据键值来进行赋值的。

    需要注意的是,对象在解构赋值时,如果已经先声明过变量了,则需要使用圆括号括起来,否则会解析出错。

  • 相关阅读:
    修复 Visual Studio Error “No exports were found that match the constraint”
    RabbitMQ Config
    Entity Framework Extended Library
    Navisworks API 简单二次开发 (自定义工具条)
    NavisWorks Api 简单使用与Gantt
    SQL SERVER 竖表变成横表
    SQL SERVER 多数据导入
    Devexpress GridControl.Export
    mongo DB for C#
    Devexress XPO xpPageSelector 使用
  • 原文地址:https://www.cnblogs.com/jiangxianfly/p/13054680.html
Copyright © 2011-2022 走看看