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);
当然,在正常情况下,这些都将是未定义
(如上所示),因为数组通常不具有这些属性。
第二个示例(对象解构),使用非数组对象:
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
更多 on MDN .
关于javascript - const [a, b, c] = array; 和有什么区别const {a, b, c} = 数组;,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59845247/