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

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

当前回答

使用ES6可以这样做…

假设你有这两个数组……

const a = ["a", "b", "c", "d", "e"];
const b = [5, 4, 3, 2, 1];

你想交换第一个值:

const [a0] = a;
a[0] = b[0];
b[0] = a0;

和值:

a; //[5, "b", "c", "d", "e"]
b; //["a", 4, 3, 2, 1]

其他回答

下面是一个变体,它首先检查数组中是否存在索引:

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;
}

如果索引不存在,它目前只会返回这个,但是您可以很容易地修改失败时的行为

如果你想要一个单一的表达式,使用本地javascript, 记住,拼接操作的返回值 包含已删除的元素。

var A = [1, 2, 3, 4, 5, 6, 7, 8, 9], x= 0, y= 1;
A[x] = A.splice(y, 1, A[x])[0];
alert(A); // alerts "2,1,3,4,5,6,7,8,9"

编辑:

当array. splice()返回一个数组时,表达式末尾的[0]是必要的,在这种情况下,我们需要返回数组中的单个元素。

就地交换

// array methods
function swapInArray(arr, i1, i2){
    let t = arr[i1];
    arr[i1] = arr[i2];
    arr[i2] = t;
}

function moveBefore(arr, el){
    let ind = arr.indexOf(el);
    if(ind !== -1 && ind !== 0){
        swapInArray(arr, ind, ind - 1);
    }
}

function moveAfter(arr, el){
    let ind = arr.indexOf(el);
    if(ind !== -1 && ind !== arr.length - 1){
        swapInArray(arr, ind + 1, ind);
    }
}

// dom methods
function swapInDom(parentNode, i1, i2){
    parentNode.insertBefore(parentNode.children[i1], parentNode.children[i2]);
}

function getDomIndex(el){
    for (let ii = 0; ii < el.parentNode.children.length; ii++){
        if(el.parentNode.children[ii] === el){
            return ii;
        }
    }
}

function moveForward(el){
    let ind = getDomIndex(el);
    if(ind !== -1 && ind !== 0){
        swapInDom(el.parentNode, ind, ind - 1);
    }
}

function moveBackward(el){
    let ind = getDomIndex(el);
    if(ind !== -1 && ind !== el.parentNode.children.length - 1){
        swapInDom(el.parentNode, ind + 1, ind);
    }
}

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

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被传递到函数之后。

如果你不想在ES5中使用临时变量,这是交换数组元素的一种方法。

var swapArrayElements = function (a, x, y) {
  if (a.length === 1) return a;
  a.splice(y, 1, a.splice(x, 1, a[y])[0]);
  return a;
};

swapArrayElements([1, 2, 3, 4, 5], 1, 3); //=> [ 1, 4, 3, 2, 5 ]