Reputation: 370
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:
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
?
Upvotes: 1
Views: 162
Reputation: 386680
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; }
Upvotes: 0
Reputation: 225074
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];
Upvotes: 3