发布于 2026-01-06 0 阅读
0

像专业人士一样使用数组解构😎

像专业人士一样使用数组解构😎

大家好👋

在上一篇文章中,我们通过示例学习了对象解构。在本文中,我将分享如何有效地使用数组解构

数组解构

数组解构有助于从数组中解包值,为变量分配默认值,并使用逗号忽略元素。

让我们通过例子来学习每个功能。

从数组中解包值。

假设我们有一个数组,其中包含一个颜色代码列表。

const colorsCode = ['r', 'g', 'b'];

Enter fullscreen mode Exit fullscreen mode

你需要创建三个变量并给它们赋值。首先,我们来看看如何在不使用数组解构的情况下实现这一点。

const red = colorsCode[0]; // r
const green = colorsCode[1]; // g
const blue = colorsCode[2]; // b
Enter fullscreen mode Exit fullscreen mode

这段代码完全没问题,可以按预期运行。它用了 4 行代码来实现。但是,使用数组解构,它可以写成一行:

const [red, green, blue] = colorsCode;
Enter fullscreen mode Exit fullscreen mode

哇,刚才发生了什么?

右侧数组(r)中的第一个值被赋值给左侧数组声明(red)中的第一个变量。以此类推,其余值也按相同方式赋值。

array-dest-1(2).png

变量的顺序应该与它在数组中的位置一致。让我们看看如果在赋值过程中改变变量的顺序会发生什么。

const [red, blue, green] = colorsCode;
console.log(red); // r
console.log(blue); // g
console.log(green); // b
Enter fullscreen mode Exit fullscreen mode

array-dest-2.png

在上面的例子中,我们交换了左侧数组中蓝色和绿色的值。由于我们改变了变量的顺序,`a`g被赋值为 `b` blue,`c`b被赋值为 `c` green。因此,请确保变量名的声明顺序与右侧数组的值一致。

为变量赋默认值

当数组为空或值不可用时,您可以为变量分配默认值。

例1:

const [red, green, blue] = []
console.log(red, green, blue); // prints undefined undefined undefined

// assign default value
const [red = 'r', green = 'g', blue = 'b'] = []
console.log(red, green, blue); // prints r g b
Enter fullscreen mode Exit fullscreen mode

例2:

const [red, green, blue] = ['r', 'g']
console.log(red, green, blue); // prints r g undefined

// assign default value for a single variable
const [red, green, blue = 'b'] = ['r' ,'g']
console.log(red, green, blue); // prints r g b

Enter fullscreen mode Exit fullscreen mode

忽略数组元素

可以使用以下方法忽略数组解构中的元素,(commas)

当我们只需要red&blue代码时,无需green在语法中声明。

const [red, blue, green] = ['r', 'g', 'b'];
Enter fullscreen mode Exit fullscreen mode

为避免创建未使用的变量blue,请替换blue,跳过赋值变量的操作。

const [red, , green] = ['r', 'g', 'b'];
Enter fullscreen mode Exit fullscreen mode

以下是忽略元素的另一个例子。这样只会创建偶数个变量。

const [ ,second, ,fourth, ,sixth, ,eight] = [1, 2, 3, 4, 5, 6, 7, 8];
Enter fullscreen mode Exit fullscreen mode

这将创建 4 个变量,分别为secondfourthsixtheight。它将根据数组顺序为变量分配相应的值。

对象解构 + 数组解构

让我们来看看同时使用对象解构和数组解构的强大之处。(:如果您还没有阅读过我的对象解构文章,请先阅读该文章。)

    const user = {
       firstName: 'John',
       lastName: 'Doe',
       phone: '9999999999',
       address: 'India',
       preferences: {
           mode: 'light', // light (or) dark mode
           autoSave: true,
           bookmarks: [ {name: 'bookmark 1', readCount: 10}, {name: 'bookmark 2'}]   
      }
  }
Enter fullscreen mode Exit fullscreen mode

我们的目标是只获取firstNamephone一个address书签name和第二个书签readCount。如果readCount该属性不可用,0则设置默认值。

如果不进行解构,我们的代码可能会变成这样:

const firstName = user.firstName;
const phone = user.phone;
const address = user.address;
const firstBookmarkName = user.preferences.bookmarks[0].name;
const secondBookmarkReadCount = user.preferences.bookmarks[1]?.count || 0;
// prints John 9999999999 India bookmark 1 0
console.log(firstName, phone, address, firstBookmarkName, secondBookmarkReadCount); 
Enter fullscreen mode Exit fullscreen mode

通过解构,它可以简化为:

const {
  firstName,
  phone,
  address,
  preferences: {
    bookmarks: [
      { name: firstBookmarkName },
      { count: secondBookmarkReadCount = 0 },
    ],
  },
} = user

// prints John 9999999999 India bookmark 1 0
console.log(firstName, phone, address, firstBookmarkName, secondBookmarkReadCount); 
Enter fullscreen mode Exit fullscreen mode

哇,是不是很棒?😍

所有的赋值、默认值和别名都写在一行里(如果没有格式化的话)。是不是很神奇?

让我解释一下从第一个书签中获取名称的逻辑。

要获取第一个书签的名称,首先,我们可以使用数组解构从数组中提取第一个元素。

const { preferences: { bookmarks: [firstBookmark] } } = user; 
console.log(firstBookmark); // prints {name: 'bookmark 1', readCount: 10},
Enter fullscreen mode Exit fullscreen mode

然后,通过对象解构,可以从对象中解包该属性name。同时,为其设置一个别名键。

const { name: firstBookmarkName } = {name: 'bookmark 1', readCount: 10};
Enter fullscreen mode Exit fullscreen mode

通过合并这两件事,我们可以简单地写成:

const { preferences: { bookmarks: [{ name: firstBookmarkName }] } } = user; 

Enter fullscreen mode Exit fullscreen mode

类似地,readCount可以先通过数组解构来获取,然后再应用对象解构。

太棒了!现代 JavaScript 让代码更简洁易读了。感谢数组和对象解构!😍🎉

奖金:

你也可以对字符串进行数组解构。

 const [d, e, v] = 'DEV';
console.log(d, e, v); // D E V
Enter fullscreen mode Exit fullscreen mode

感谢阅读我的文章。如果您喜欢我的文章,请分享给您的朋友!

文章来源:https://dev.to/yuvgeek/use-array-destructuring-like-a-pro-d53