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

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

当前回答

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

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

其他回答

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

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]

就地交换

// 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 b = list[y];
list[y] = list[x];
list[x] = b;

10年后,随着ES6的大量采用,编辑劫持了最重要的答案:

给定数组arr =[1,2,3,4],你现在可以在一行中交换值,如下所示:

[arr[0], arr[1]] = [arr[1], arr[0]];

这将产生数组[2,1,3,4]。这是解构赋值。

如果你不想在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 ]

如果你想要一个单一的表达式,使用本地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]是必要的,在这种情况下,我们需要返回数组中的单个元素。