交换数组中两个元素的位置多种方法

69 阅读1分钟
function swapArrayItems (data<Array>,index1,index2) { 
    const currentItem = data[index1];
    const previousItem = data[index2]; 
    // 交换位置
    data[index1] = previousItem;
    data[index2] = currentItem; 
}

这是一个基础的交换数组中两个元素的位置方法。其他方法如下

1. 使用临时变量

function swapArrayItems(data, index1, index2) {
    const temp = data[index1];
    data[index1] = data[index2];
    data[index2] = temp;
}

这是最基础的方式,通过一个临时变量来保存一个值,然后再进行交换。

2. 使用数组解构赋值

function swapArrayItems(data, index1, index2) {
    [data[index1], data[index2]] = [data[index2], data[index1]];
}

这是 ES6 中的解构赋值语法,通过这一行代码就可以完成元素的交换。

3. 使用 XOR 位运算

function swapArrayItems(data, index1, index2) {
    data[index1] = data[index1] ^ data[index2];
    data[index2] = data[index1] ^ data[index2];
    data[index1] = data[index1] ^ data[index2];
}

XOR 位运算的方式不需要额外的空间,但是这种方式只适用于数值类型的数据。

4. 使用 Array.prototype.splice()

function swapArrayItems(data, index1, index2) {
    const temp = data[index1];
    data.splice(index1, 1, data[index2]);
    data.splice(index2, 1, temp);
}

使用 splice 方法进行数组元素的交换,splice 方法会移除和插入元素。

5. 使用临时数组

function swapArrayItems(data, index1, index2) {
    const tempArray = [data[index1], data[index2]];
    data[index1] = tempArray[1];
    data[index2] = tempArray[0];
}

将要交换的元素放入一个临时数组,然后再从临时数组中取出并赋值到原数组的目标位置。

这些方法根据实际情况可以灵活选择。最常用且简洁的方法是解构赋值,尤其是在不涉及复杂的数据类型时。