解构赋值(代码简洁之道)

这是我参与8月更文挑战的第14天,活动详情查看: 8月更文挑战 ​

序言

一说到解构赋值,第一想到肯定是对象了,但是JS中最常用的数据结构除了Object对象,还有Array数组。解构赋值 是ES6 的新语法,他是我们可以将数组或者对象拆分到一系列的变量中,这样可以是某些情况下使用变量更加方便简洁。

数组解构

我们先看一个数组解构到变量的例子

/ 我们有一个存放了名字和性别的数组
let arr = ["coolFish", "男"]// 正常操作
// set name = arr[0]
// set sex = arr[1]// 解构赋值
let [name, sex] = arr;
​
alert(name); // coolFish
alert(sex);  // 男
复制代码

数组的结构还可以配合 splice 等函数一起使用

let [name, sex] = "coolFish 男".splice(' ')
//结果  name = coolFish  sex = "男"
复制代码

如果想要精简一个数组,例如我不想要第二个元素,那么我们可以使用一个空位跳过他

let [name, , sex] = ["coolFish", "24岁", "男"];
​
alert( sex ); // 男
复制代码

赋值给左侧任意内容,不仅仅是只能赋值给变量

let people = {};
[people.name, people.age] = "coolFish 男".split(' ');
​
alert(user.name); // coolFish
复制代码

与对象的 .entries 方法可以进行循环操作 ​

let user = {
  name: "coolFish",
  age: 25
};
​
// 循环遍历键—值对
for (let [key, value] of Object.entries(user)) {
  alert(`${key}:${value}`); //1: name:coolFish  //2:  age:30
}
复制代码

还可以用来交换变量,记得有个面试题,如何将a,b的值互换,最简单的做法如下

let a = 1
let b = 2
[a, b] = [b, a]
复制代码

数组的剩余元素 ​

如果我们只想获取前几个元素,剩下的元素收集起来,我们可以用...再加一个参数来接受剩余参数

let [name1, name2, ...extra] = ["coolFish", "coolFish", "teacherGuo","smilken"];
​
alert(name1); // coolFish
alert(name2); // coolFish// 请注意,`rest` 的类型是数组
alert(rest[0]); // teacherGuo
alert(rest[1]); // smilken
alert(rest.length); // 2
复制代码

默认值

如果赋值语句中,变量的数量多于数组中实际元素的数量,赋值不会报错。未赋值的变量被认为是 undefined

let [name, sex] = [];
​
alert(name); // undefined
alert(sex); // undefined
复制代码

如果我们想要一个“默认”值给未赋值的变量,我们可以使用 = 来提供

// 默认值
let [name = "coolFish", sex = "男"] = ["teacherGuo"];

alert(name);    // teacherGuo(来自数组的值)
alert(sex); // 男(默认值被使用了)
复制代码

对象结构

相对数组解构,我们平常对象结构用的会更多

let coolFish = {
  age: "25",
  sex: '男',
  height: 178
};

let {age, sex, height} = coolFish;

alert(age);  // 25
alert(sex);  // 男
alert(height); // 178
复制代码

属性 coolFish.titlecoolFish.widthcoolFish.height 值被赋给了对应的变量。变量的顺序并不重要,下面这个代码也奏效:

let coolFish = {
  age: "25",
  sex: '男',
  height: 178
};

let {height,age, sex, } = coolFish;

alert(age);  // 25
alert(sex);  // 男
alert(height); // 178
复制代码

如果我们想把一个属性解构并赋值给另外一个名字的变量,例如把 coolFish.height 赋值给 H,我们可以用冒号来指定

let coolFish = {
  age: "25",
  sex: '男',
  height: 178
};


let {height:H,age:A, sex, } = coolFish;

// height -> H
// age -> A
// sex -> 男

alert(H);  // 178
alert(A);  // 25
alert(sex) // 男
复制代码

为了防止缺失属性的解构出错

let coolFish = {
  age: "25"
};
​
let {width = 100, height = 200, age} = options;
​
alert(age);  // 25
alert(width);  // 100
alert(height); // 200
复制代码

如果我们想要一个属性解构并赋值给另外一个名字的变量,并且设置默认值,可以将冒号和等号联合使用

let coolFish = {
  age: "25"
};
​
let {width : W = 100, height : H = 200, age} = options;
​
alert(age);  // 25
alert(W);  // 100
alert(H); // 200
复制代码
分类:
前端