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:52

Here is a variation that first checks if the index exists in the array:

Array.prototype.swapItems = function(a, b){
    if(  !(a in this) || !(b in this) )
        return this;
    this[a] = this.splice(b, 1, this[a])[0];
    return this;
}

It currently will just return this if the index does not exist, but you could easily modify behavior on fail

查看更多
看淡一切
3楼-- · 2019-01-01 15:53

Consider such a solution without a need to define the third variable:

function swap(arr, from, to) {
  arr.splice(from, 1, arr.splice(to, 1, arr[from])[0]);
}

var letters = ["a", "b", "c", "d", "e", "f"];

swap(letters, 1, 4);

console.log(letters); // ["a", "e", "c", "d", "b", "f"]

Note: You may want to add additional checks for example for array length. This solution is mutable so swap function does not need to return a new array, it just does mutation over array passed into.

查看更多
几人难应
4楼-- · 2019-01-01 15:55

This didn't exist when the question was asked, but ES2015 introduced array destructuring, allowing you to write it as follows:

let a = 1, b = 2;
// a: 1, b: 2
[a, b] = [b, a];
// a: 2, b: 1
查看更多
荒废的爱情
5楼-- · 2019-01-01 15:57

For the sake of brevity, here's the ugly one-liner version that's only slightly less ugly than all that concat and slicing above. The accepted answer is truly the way to go and way more readable.

Given:

var foo = [ 0, 1, 2, 3, 4, 5, 6 ];

if you want to swap the values of two indices (a and b); then this would do it:

foo.splice( a, 1, foo.splice(b,1,foo[a])[0] );

For example, if you want to swap the 3 and 5, you could do it this way:

foo.splice( 3, 1, foo.splice(5,1,foo[3])[0] );

or

foo.splice( 5, 1, foo.splice(3,1,foo[5])[0] );

Both yield the same result:

console.log( foo );
// => [ 0, 1, 2, 5, 4, 3, 6 ]

#splicehatersarepunks:)

查看更多
余生无你
6楼-- · 2019-01-01 15:58

Digest from http://www.greywyvern.com/?post=265

var a = 5, b = 9;    
b = (a += b -= a) - b;    
alert([a, b]); // alerts "9, 5"
查看更多
伤终究还是伤i
7楼-- · 2019-01-01 15:58

If need swap first and last elements only:

array.unshift( array.pop() );
查看更多
登录 后发表回答