首页 > 解决方案 > const [a, b, c] = array 有什么区别?和 const {a, b, c} = 数组;

问题描述

const [a, b, c] = array; 

const {a, b, c} = array;

问:这两种说法有什么区别?

标签: javascriptreactjstypescriptvue.js

解决方案


第一个是可迭代解构a将获得 中的第一个值arrayb将获得第二个值,并将c获得第三个值。

二是对象解构a将获得 的值array.ab将获得 的值array.bc并将获得 的值array.c。(通常不是您想要的数组。)

第一个例子:

const [a, b, c] = ["ay", "bee", "see"];
console.log(a, b, c);

该示例使用数组,但源可以是任何可迭代对象。

第二个示例(对象解构),带有一个数组:

const array = ["ay", "bee", "see"];
const {a, b, c} = array;
console.log(a, b, c);

当然,在正常情况下,这些都是undefined(如上所示),因为数组通常不具有这些属性。

第二个示例(对象解构),具有非数组对象:

const obj = {a: "ayy", b: "bee", c: "see"};
const {a, b, c} = obj;
console.log(a, b, c);

尽管可以,但通常不会对数组使用对象解构,因为数组是对象。当您想从数组中挑选特定条目时,它很有用,例如这段代码挑选索引 2 和 4 处的值:

const array = ["ay", "bee", "see", "dee", "eee"];
const {2: c, 4: e} = array;
console.log(c, e); // "see" "eee"

您甚至可以使用解构模式中的计算属性表示法对来自变量的索引执行此操作:

const array = ["ay", "bee", "see", "dee", "eee"];
const indexA = Math.floor(Math.random() * array.length);
const indexB = Math.floor(Math.random() * array.length);
const {[indexA]: a, [indexB]: b} = array;
console.log(`${indexA}: ${a}, ${indexB}: ${b}`); // Varies depending on the random indexes

更多关于 MDN的信息。


推荐阅读