Naw*_*Ali 5 javascript typescript reactjs vue.js
const [a, b, c] = array;
const {a, b, c} = array;
Run Code Online (Sandbox Code Playgroud)
问:这两种说法有什么不同?
T.J*_*der 12
第一个是可迭代解构。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);
Run Code Online (Sandbox Code Playgroud)
该示例使用数组,但源可以是任何可迭代对象。
第二个示例(对象解构),使用数组:
const array = ["ay", "bee", "see"];
const {a, b, c} = array;
console.log(a, b, c);
Run Code Online (Sandbox Code Playgroud)
在正常情况下,当然,这些都将是undefined
(如上所示),因为数组通常不具有这些属性。
第二个示例(对象解构),使用非数组对象:
const obj = {a: "ayy", b: "bee", c: "see"};
const {a, b, c} = obj;
console.log(a, b, c);
Run Code Online (Sandbox Code Playgroud)
您通常不会对数组使用对象解构,尽管您可以,因为数组是对象。当您想从数组中挑选特定条目时,它很有用,例如以下代码挑选索引 2 和 4 处的值:
const array = ["ay", "bee", "see", "dee", "eee"];
const {2: c, 4: e} = array;
console.log(c, e); // "see" "eee"
Run Code Online (Sandbox Code Playgroud)
您甚至可以使用解构模式中的计算属性符号对来自变量的索引执行此操作:
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
Run Code Online (Sandbox Code Playgroud)
更多关于 MDN。
归档时间: |
|
查看次数: |
1176 次 |
最近记录: |