一文讲清 ES6 中的解构赋值

解构赋值

认识解构赋值

解构赋值是一种 JavaScript 表达式,它允许我们从数组或对象中提取数据并赋值给独立的变量。简单来说,通过解构,我们可以简化从复杂对象或数组中提取数据的过程,同时完成变量声明和赋值。

使用场景

假设我们需要展示某个商店的信息,这些信息存储在一个名为 store 的对象中——这个对象包含了商店名称、员工数量和三个分店的地址。在没有使用解构赋值之前,我们可能会这样编写 JavaScript 代码:

const store = {
  name'Mr. Mike Coffee',
  employees100,
  locations: {
    china'中国地址',
    singapore'新加坡地址',
    sanFrancisco'旧金山地址'
  }
};

function displayStoreInfo(store{
  console.log(`您正在查找的商店是:${store.name}`);
  console.log(`目前该商店有 ${store.employees} 名员工`);
  console.log(`中国分店地址:${store.locations.china}`);
  console.log(`新加坡分店地址:${store.locations.singapore}`);
  console.log(`旧金山分店地址:${store.locations.sanFrancisco}`);
}

displayStoreInfo(store);

虽然这种方法最终可以展示商店信息,但在编写代码时,我们可能会发现需要编写很多代码来获取对象中的特定信息,例如 store.locations.singapore。使用解构赋值可以使代码更简洁、易读。让我们先看看使用解构赋值后的代码示例:

function displayStoreInfo({ name, employees, locations: { china, singapore, sanFrancisco } }{
  console.log(`您正在查找的商店是:${name}`);
  console.log(`目前该商店有 ${employees} 名员工`);
  console.log(`中国分店地址:${china}`);
  console.log(`新加坡分店地址:${singapore}`);
  console.log(`旧金山分店地址:${sanFrancisco}`);
}

接下来,我将通过一些示例来介绍解构赋值,并在最后回顾这个例子,以帮助您快速理解解构赋值的好处:

数组解构赋值

语法介绍法

  • 在数组解构赋值中,被解构的数组位于等号的右侧。
  • 需要赋值的变量位于等号的左侧,变量的位置需要与数组中的值相对应。

基本变量赋值

通过数组解构,我们可以将 scores 数组中的三个值分别赋给 math、science 和 history 这三个变量:

const scores = [1009095];
const [math, science, history] = scores; // math = 100, science = 90, history = 95

变量交换

除了基本赋值,解构赋值还可以用于变量交换。例如,如果我们想在下雨天交换午餐和晚餐的内容:

let lunch = '牛肉面';
let dinner = '鸡肉咖哩饭';
let raining = true;

if (raining) {
  [lunch, dinner] = [dinner, lunch];
}

console.log(`${lunch} -> ${dinner}`); // 鸡肉咖哩饭 -> 牛肉面

初次看到这个方法可能会觉得有点抽象,或是不可思议。但如果搭配前一项「基本变量赋值」的使用,把过程拆解出来,会容易理解许多:

let lunch = '牛肉面';
let dinner = '鸡肉咖哩饭';
let raining = true

// 如同「基本变量赋值」,先把数组准备好:将午晚餐存放在 meal 数组中
const meal = [lunch, dinner]

if (raining) {
  // 如同「基本变量赋值」,将 meal 数组解构取得值后,赋予到左边数组中相对位置
  // 由于 dinner 和 lunch 已经被声明过,因此数组前不需要使用 let / const
  [dinner, lunch] = meal
}

console.log(`$lunch -> $dinner`// 鸡肉咖哩饭 -> 牛肉面

忽略某些值

在解构赋值时,我们可以选择忽略数组中的某些值:

const scores = [1009095];
const [math, , history] = scores; // math = 100, history = 95(忽略90)

解构嵌套数组

当要解构嵌套类型的数组,嵌套数组相对应的位置也必须是数组,才能够成功把值赋予正确的变量。在以下例子中,想把 90 和 93 两个分数,赋予给 firstHistory 和 secondHistory 两个变量:

const scores = [100, [9093], 95]
const [math, [firstHistory, secondHistory]] = scores
console.log(`${math}${firstHistory}${secondHistory}`//100, 90, 93

对象解构赋值

对象解构赋值和数组解构赋值非常相似,所以在了解数组解构赋值后,要理解对象解构赋值就会相对容易许多:

基本解构赋值

通过使用 store 对象中相对应的属性名称,我们创建了 name 和 employees 两个变量,并取出在 store 对象中对应的属性值,存在各自的变量当中。

const store = {
  name'Mr.r Mike Coffee',
  employees100
}
const { name, employees } = store // name = Mr.r Mike Coffee, employees = 100

指定新的变量名称

在前一个例子中,我们将取出来的值,赋予与 store 对象中属性名称相同的变量,但在一些情况下,我们会希望将取出来的值,赋予不同的变量名称,这时可以通过使用:{objectKeyName: newVariableName}

const store = {
  name'Mr.r Mike Coffee',
  employees100
}
const { name: storeName, employees: employeesNum } = store
console.log(`${storeName}${employeesNum}`//Mr.r Mike, Coffee 100

给定默认值

当变量无法在要解构的对象中找到相对应的属性时,将会是 undefined,因此我们可以给予变量一个「默认值」来处理值为 undefined 的状况(默认值只有在对应 undefined 时,才会被用上)

在上述例子中,我们给 ceo 一个默认值 Mike。由于 store 对象中没有 ceo 这个属性,因此 ceo 被赋予默认值 Mike。

const store = {
  name'Mr.r Mike Coffee',
  employees100
}

const { name: storeName, employees: employeesNum, ceo = 'Mike' } = store

console.log(`${storeName}${employeesNum}${ceo}`//Mr.r Mike Coffee, 100, Mike

搭配函数的入参使用

解构赋值也可以运用在要带入函数的参数上 — 若带入函数的参数为一个对象时,特别好用!

举商店的例子来说,若带入 displayStoreInfo 的参数为 store 对象,而我们想要解构这个 store 对象 — 取出特定的属性值,并赋予 name 和 employees 两个变量 — 我们可以这么写:

const store = {
 name'Mr.r Mike Coffee',
 employees100,
 location'Address, china'
}

function displayStoreInfo(store{
 const {name, employees} = store
  console.log(`您正在查找的商店是:${name}`);
  console.log(`目前该商店有 ${employees} 名员工`);
}

displayStoreInfo(store)

在以上的例子中,的确我们可以在 displayStoreInfo 函数接受到 store 参数后,在函数中编写一行程式码(第八列)来解构 store 对象,但其实有更简洁的方式:在函数的参数列表中直接解构接收到的对象,取出在这个函数中需要用到的属性值 — 例如只需要使用对象中 name 和 employees 两个数据 — 赋予参数:

const store = {
  name'Mr.r Mike Coffee',
  employees100,
  location'Address, china'
}
function displayStoreInfo({ name, employees }{
  console.log(`您正在查找的商店是:${name}`);
  console.log(`目前该商店有 ${employees} 名员工`);
}

displayStoreInfo(store);

结语

解构赋值是 ES6 引入的新特性,它使得从数组和对象中提取和使用数据变得更加方便,同时提高了代码的可读性。虽然一开始可能不太习惯这种语法结构,但通过一些实践,您将很快能够掌握它,并感受到它带来的便利。


原文始发于微信公众号(程序猿技术充电站):一文讲清 ES6 中的解构赋值

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

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

(0)
小半的头像小半

相关推荐

发表回复

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