[英]Array destructuring via spread operator
The MDN documentation concerning array destructuring is pretty self-explanatory, however, I fail to understand what is happening behind the scenes when destructuring an array like so: 关于数组解构的MDN文档是非常不言自明的,但是,我无法理解在解构数组时幕后发生的事情:
let Arr = [1, 3, 5, 6]; let newArr = []; [newArr[0], ...newArr] = Arr; console.log(Arr); // returns [1, 3, 5, 6] console.log(newArr); // returns [3, 5, 6]
How is it that newArr
does not inherit the first array member of Arr
? newArr
如何不继承Arr
的第一个数组成员?
If you had 如果你有
[x, ...y] = Arr;
it would be like 它会是这样的
x = Arr[0];
y = Arr.slice(1);
so when you have 所以当你有
[newArr[0], ...newArr] = Arr;
it's like 就像是
newArr[0] = Arr[0];
newArr = Arr.slice(1);
The assignments involved in destructuring happen left to right. 解构涉及的任务从左到右发生。 Live:
生活:
const listener = { get foo() { return { set bar(value) { console.log('setting bar'); }, }; }, set foo(value) { console.log('setting foo'); }, }; [listener.foo.bar, ...listener.foo] = [1, 2, 3];
It works, but it overwrites with the rest parameters the first value on index zero. 它有效,但它用其余参数覆盖索引零的第一个值。
let array0 = [1, 3, 5, 6], array1 = [], array2 = []; [array2[0], ...array1] = array0; console.log(array0); // [1, 3, 5, 6] console.log(array1); // [3, 5, 6] console.log(array2); // [1]
.as-console-wrapper { max-height: 100% !important; top: 0; }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.