Just for the fun of it, another way without using any extra variable would be:
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
// swap index 0 and 2
arr[arr.length] = arr[0]; // copy idx1 to the end of the array
arr[0] = arr[2]; // copy idx2 to idx1
arr[2] = arr[arr.length-1]; // copy idx1 to idx2
arr.length--; // remove idx1 (was added to the end of the array)
console.log( arr ); // -> [3, 2, 1, 4, 5, 6, 7, 8, 9]
According to some random person on Metafilter,
"Recent versions of Javascript allow you to do swaps (among other things) much more neatly:"
[ list[x], list[y] ] = [ list[y], list[x] ];
My quick tests showed that this Pythonic code works great in the version of JavaScript
currently used in "Google Apps Script" (".gs").
Alas, further tests show this code gives a "Uncaught ReferenceError: Invalid left-hand side in assignment." in
whatever version of JavaScript (".js") is used by
Google Chrome Version 24.0.1312.57 m.
Just for the fun of it, another way without using any extra variable would be:
what about Destructuring_assignment
which can also be extended to
You can swap elements in an array the following way:
See the following example:
Note: it works the same way for regular variables
Here's a one-liner that doesn't mutate
list
:let newList = Object.assign([], list, {[x]: list[y], [y]: list[x]})
(Uses language features not available in 2009 when the question was posted!)
To swap two consecutive elements of array
According to some random person on Metafilter, "Recent versions of Javascript allow you to do swaps (among other things) much more neatly:"
My quick tests showed that this Pythonic code works great in the version of JavaScript currently used in "Google Apps Script" (".gs"). Alas, further tests show this code gives a "Uncaught ReferenceError: Invalid left-hand side in assignment." in whatever version of JavaScript (".js") is used by Google Chrome Version 24.0.1312.57 m.