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

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

当前回答

摘要:http://www.greywyvern.com/?post=265

var a = 5, b = 9;    
b = (a += b -= a) - b;    
alert([a, b]); // alerts "9, 5"

其他回答

好吧,你不需要缓冲两个值-只有一个:

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

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

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

Array.prototype.swap = function(a, b) {
  var temp = this[a];
  this[a] = this[b];
  this[b] = temp;
};

用法:

var myArray = [0,1,2,3,4...];
myArray.swap(4,1);

就地交换

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