[英]ES6 destructuring: Array reordering mechanism
I was reading through Kyle Simpson's book (You don't Know JS - ES6 and beyond) and he gives this example on reordering arrays: 我正在阅读Kyle Simpson的书(您不了解JS-ES6及更高版本) ,他给出了有关对数组重新排序的示例:
var a1 = [ 1, 2, 3 ],
a2 = [];
[ a2[2], a2[0], a2[1] ] = a1;
console.log( a2 ); // [2,3,1]
Can someone help me understand what's happening (I was expecting it to return [3, 1, 2]). 有人可以帮助我了解正在发生的事情吗(我希望它返回[3,1,2])。 If I input other elements, it gets more confusing:
如果我输入其他元素,则会变得更加混乱:
[ a2[2], a2[0], a2[0] ] = a1; // [3, undefined, 1]
[ a2[1], a2[0], a2[0] ] = a1; // [3, 1]
You can use Babel's REPL to find out what the code compiles down to. 您可以使用Babel的REPL来找出代码编译成的内容。 (I've annotated the output with additional comments.)
(我在输出中附加了注释。)
var a1 = [1, 2, 3],
a2 = [];
a2[2] = a1[0]; // a1[0] = 1
a2[0] = a1[1]; // a1[1] = 2
a2[1] = a1[2]; // a1[2] = 3
console.log(a2); // [2,3,1]
The positions in the destructuring pattern map to the indexes in the source array. 解构模式中的位置映射到源数组中的索引。 So it's equivalent to:
因此,它等效于:
a2[2] = a1[0];
a2[0] = a1[1];
a2[1] = a1[2];
The result you were expecting would come from: 您期望的结果将来自:
a2 = [ a1[2], a1[0], a1[1] ];
This is the opposite of destructuring. 这与销毁相反。
This one: 这个:
[ a2[2], a2[0], a2[0] ] = a1;
never assigns to a2[1]
, so you get undefined for that element. 从不分配给
a2[1]
,因此您对该元素未定义。 You assign to a2[0]
twice, first from 2
and then from 3
, so the final value is 3
. 您两次分配
a2[0]
,首先是2
,然后是3
,所以最终值为3
。
It's actually quite simple. 实际上很简单。
Destructing an array in ES6 is basically like this: 在ES6中销毁数组基本上是这样的:
If you have 如果你有
var arr = [1, 2, 3, 4];
This means that when you write something like 这意味着当您编写类似
[a, b, c, d] = arr;
You are actually saying this 你其实是在说这个
a = arr[0];
b = arr[1];
c = arr[2];
d = arr[3];
Notice that the position of a
, b
, c
or d
corresponds to the index of the array arr
, such that if you write 请注意,
a
, b
, c
或d
对应于数组arr
的索引,因此,如果您编写
[a, c, b, d] = arr;
What you really mean is 你真正的意思是
a = arr[0];
c = arr[1];
b = arr[2];
d = arr[3];
It just combine two steps of destructuring and adding values to arr2
in one step. 它只是将
arr2
和将值添加到arr2
两个步骤结合在一起。 It is same as if you did this. 就像您执行此操作一样。
var a1 = [1, 2, 3], a2 = []; var [one, two, three] = a1; a2[0] = two; a2[1] = three; a2[2] = one console.log(a2)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.