是否有更简单的方法来交换数组中的两个元素?

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

当前回答

可以通过以下方式交换数组中的元素:

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

示例如下:

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

注意:它的工作方式与常规变量相同

var a=1,b=5;
a = [b,b=a][0]

其他回答

如果你因为某些原因不允许使用就地交换,这里有一个map的解决方案:

函数swapElements(数组,源,dest) { 返回源=== dest ? Array:阵列。Map ((item, index) => index === source ? 数组[dest]: index === dest ? 数组[来源]:item); } Const arr = ['a', 'b', 'c']; const s1 = swapElements(arr, 0,1); Console.log (s1[0] === 'b'); Console.log (s1[1] === 'a'); const s2 = swapElements(arr, 2,0); Console.log (s2[0] === 'c'); Console.log (s2[2] === 'a');

下面是快速复制粘贴的typescript代码:

function swapElements(array: Array<any>, source: number, dest: number) {
  return source === dest
    ? array : array.map((item, index) => index === source
      ? array[dest] : index === dest 
      ? array[source] : item);
}

有一种有趣的交换方式:

var a = 1;
var b = 2;
[a,b] = [b,a];

(ES6 way)

这似乎还可以....

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

不管用

var b = list[y];

意味着变量b将在作用域的其余部分出现。这可能会导致内存泄漏。不太可能,但还是最好避免。

也许把这个放到array。prototype。swap中是个好主意

Array.prototype.swap = function (x,y) {
  var b = this[x];
  this[x] = this[y];
  this[y] = b;
  return this;
}

它可以被称为:

list.swap( x, y )

这是一种既避免内存泄漏又避免DRY的干净方法。

你可以交换任意数量的对象或文字,甚至是不同类型的对象或文字,使用一个简单的恒等函数,如下所示:

var swap = function (x){return x};
b = swap(a, a=b);
c = swap(a, a=b, b=c);

针对你的问题:

var swap = function (x){return x};
list[y]  = swap(list[x], list[x]=list[y]);

这在JavaScript中是可行的,因为它接受额外的参数,即使它们没有声明或使用。赋值a=b等,发生在a被传递到函数之后。

var a = [1,2,3,4,5], b=a.length;

for (var i=0; i<b; i++) {
    a.unshift(a.splice(1+i,1).shift());
}
a.shift();
//a = [5,4,3,2,1];