Javascript swap array elements

2019-01-01 15:36发布

Is there any simpler way to swap two elements in an array?

var a = list[x], b = list[y];
list[y] = a;
list[x] = b;

26条回答
其实,你不懂
2楼-- · 2019-01-01 15:47

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]

查看更多
不流泪的眼
3楼-- · 2019-01-01 15:48

what about Destructuring_assignment

var arr = [1, 2, 3, 4]
[arr[index1], arr[index2]] = [arr[index2], arr[index1]]

which can also be extended to

[src order elements] => [dest order elements]
查看更多
旧人旧事旧时光
4楼-- · 2019-01-01 15:49

You can swap elements in an array the following way:

list[x] = [list[y],list[y]=list[x]][0]

See the following example:

list = [1,2,3,4,5]
list[1] = [list[3],list[3]=list[1]][0]
//list is now [1,4,3,2,5]

Note: it works the same way for regular variables

var a=1,b=5;
a = [b,b=a][0]
查看更多
怪性笑人.
5楼-- · 2019-01-01 15:49

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!)

查看更多
骚的不知所云
6楼-- · 2019-01-01 15:51

To swap two consecutive elements of array

array.splice(IndexToSwap,2,array[IndexToSwap+1],array[IndexToSwap]);
查看更多
梦醉为红颜
7楼-- · 2019-01-01 15:52

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.

查看更多
登录 后发表回答