javascript - Swap tuple elements with destructuring assignments -
i thought swap elements of tuple in place using destructuring assignment follows:
var = [1,2]; [a[1], a[0]] = a;
however, yields [1, 1]
.
babel compiles as
a[1] = a[0]; a[0] = a[1];
i have thought should compiled as
let tmp0 = a[0]; let tmp1 = a[1]; a[0] = tmp1; a[1] = tmp0;
traceur behaves identically babel. guess specified behavior?
i want swap 2 elements in place. way...
let tmp = a[0]; a[0] = a[1]; a[1] = tmp;
but thought above destructuring assignment supposed let me avoid having do.
i'm capable of reversing order of 2 elements of array, not question. simple a.push(a.shift())
, meets criteria of swapping being in-place.
i'm interested here in why destructuring doesn't work way seems ought to.
i'd use function this
let swap = ([a,b]) => [b,a]; swap([1,2]); // => [2,1]
Comments
Post a Comment