ES6 解构赋值 All In One

ES6 解构赋值 All In One

解构赋值

JavaScript 中最常用的两种数据结构是 Object 和 Array。

对象让我们能够创建通过键来存储数据项的单个实体,数组则让我们能够将数据收集到一个有序的集合中。

但是,当我们把它们传递给函数时,它可能不需要一个整体的对象/数组,而是需要单个块。

解构赋值 是一种特殊的语法,它使我们可以将数组或对象“拆包”为到一系列变量中,因为有时候使用变量更加方便。
解构操作对那些具有很多参数和默认值等的函数也很奏效。

优缺点

解构赋值是对赋值运算符的扩展。

他是一种针对数组或者对象进行模式匹配,然后对其中的变量进行赋值。

在代码书写上简洁且易读,语义更加清晰明了;也方便了复杂对象中数据字段获取。

  1. 简洁且易读
        async getBlockData () {
            this.initChart();
            this.localData = [];
            this.chartLoading = true;
            const params = this.getParams();
            const res = await Table2DataGlobalService.getRealtimeData(this.apiType, params).finally(() => {
                this.chartLoading = false;
            });
            // console.log('res =', res,);
            // console.log('res.data =', res.data);
            const {
                data: {
                    data: rows,
                    last_updated,
                    meta: {
                        starttime,
                        endtime,
                    },
                },
            } = res;
            this.localData = rows;
            this.chartsData1 = this.formatChartData(rows, this.appType);
            this.chartsData2 = this.formatChartData(rows, this.payType);
            if (last_updated) {
                // 日期转换
                this.lastUpdateTime = this.$dayjs(last_updated).format('YYYY年MM月DD日 HH:mm');
            }
        },


  1. this.filterData. shit ❌
getParams () {
    // return {
    //     starttime: '2021-07-24',
    //     endtime: '2021-07-30',
    //     game_id: 10043,
    //     store_id: '',
    //     region_id: '',
    //     app_id: '',
    //     filter_fraud: 1,
    //     tz: 8,
    // };
    return {
        starttime: this.filterData.starttime,
        endtime: this.filterData.endtime,
        game_id: this.filterData.gameId,
        store_id: this.filterData.storeId,
        region_id: this.filterData.regionIds,
        app_id: this.filterData.packageIds,
        filter_fraud: this.filterData.isFraud,
        tz: this.filterData.timezone,
    };
},


TL 不要使用 ES6 解构赋值,不符合团队规范,代码维护性差 ???

WTF, SB

refs

https://zh.javascript.info/destructuring-assignment

https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment



©xgqfrms 2012-2020

www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!

原创文章,版权所有©️xgqfrms, 禁止转载 ️,侵权必究⚠️!


xgqfrms
原文地址:https://www.cnblogs.com/xgqfrms/p/15224955.html