what is the difference between const [a, b, c] = array; and


const [a, b, c] = array; 
const {a, b, c} = array;

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

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

二是对象解构a将得到array.a的值,b将得到array.b的值,c将得到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 的信息。

这些是 ES6 Javascript 中的数组解构和对象解构。

为了举例说明,

const [a, b, c] = [10, 11, 12];
From the above array destructuring statement: 
a, b and c are the variables declared and intialized with 10, 11 and 12 values respectively.
const person = {
first: 'abc',
last: 'def',
};
const {first, last} = person;
From the above object destructuring statement, 
first and last are varialbes declared and initialised with 'abc' and 'def' respectively.
The variable first and second accessed (gets the value) like person.first and person.last respectively

示例1是数组解构,它将数组元素(array[0]等(分配给相应的变量。它仅适用于可迭代对象,这些数组是:

const array = [0, 1];
const [a, b] = array;
// a === 0; 
// b === 1;

示例 2 是对象解构,它将对象键值分配给相应的变量。由于数组是 JS 中的对象,因此const {a, b} = ...对象解构仅适用于具有非数字键的数组:

const array = [0, 1];
array.a = 'a';
array.b = 'b';    
const {a, b} = array;
// a === 'a'; 
// b === 'b';

对象解构实际上可用于解构数组,因为它们是由数字键组成的对象:

const array = [0, 1];
const {0: a, 1: b} = array;
// a === 0; 
// b === 1;

最新更新