在JavaScript中交换数组元素

342
有没有一种更简单的方法来交换数组中的两个元素?
var a = list[x], b = list[y];
list[y] = a;
list[x] = b;

ES2023 数组方法 with() 可以在一行中完成:list.with(x,list[y]).with(y,list[x]) 看看我的答案和示例! - XMehdi01
ES2023 数组方法 with() 可以在一行中完成:list.with(x,list[y]).with(y,list[x]) 看看我的回答,附带一个示例! - undefined
36个回答

0
现在,您可以将数组元素交换到不同的随机位置。
function swapRandomValues(arr, numValues) {
  if (numValues > arr.length / 2) {
    console.log("Cannot swap more than half of the array.");
    return;
  }
  for (let i = 0; i < numValues; i++) {
    let randomIndex1 = Math.floor(Math.random() * arr.length);
    let randomIndex2 = Math.floor(Math.random() * arr.length);
    [arr[randomIndex1],arr[randomIndex2]] = [arr[randomIndex2],arr[randomIndex2]]
  }
  console.log(arr);
}

let arr = [1,2,3,4,5,6,7,8,9,10,11,12];
swapRandomValues(arr, 6);

-1

仅仅为了好玩,另一种不使用任何额外变量的方法是:

var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];

// swap index 0 and 2
arr[arr.length] = arr[0];   // copy idx1 to the end of the array
arr[0] = arr[2];            // copy idx2 to idx1
arr[2] = arr[arr.length-1]; // copy idx1 to idx2
arr.length--;               // remove idx1 (was added to the end of the array)


console.log( arr ); // -> [3, 2, 1, 4, 5, 6, 7, 8, 9]


-1

尝试这个函数...

$(document).ready(function () {
        var pair = [];
        var destinationarray = ['AAA','BBB','CCC'];

        var cityItems = getCityList(destinationarray);
        for (var i = 0; i < cityItems.length; i++) {
            pair = [];
            var ending_point = "";
            for (var j = 0; j < cityItems[i].length; j++) {
                pair.push(cityItems[i][j]);
            }
            alert(pair);
            console.log(pair)
        }

    });
    function getCityList(inputArray) {
        var Util = function () {
        };

        Util.getPermuts = function (array, start, output) {
            if (start >= array.length) {
                var arr = array.slice(0);
                output.push(arr);
            } else {
                var i;

                for (i = start; i < array.length; ++i) {
                    Util.swap(array, start, i);
                    Util.getPermuts(array, start + 1, output);
                    Util.swap(array, start, i);
                }
            }
        }

        Util.getAllPossiblePermuts = function (array, output) {
            Util.getPermuts(array, 0, output);
        }

        Util.swap = function (array, from, to) {
            var tmp = array[from];
            array[from] = array[to];
            array[to] = tmp;
        }
        var output = [];
        Util.getAllPossiblePermuts(inputArray, output);
        return output;
    }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


-1
function moveElement(array, sourceIndex, destinationIndex) {
    return array.map(a => a.id === sourceIndex ? array.find(a => a.id === destinationIndex): a.id === destinationIndex ? array.find(a => a.id === sourceIndex) : a )
}
let arr = [
{id: "1",title: "abc1"},
{id: "2",title: "abc2"},
{id: "3",title: "abc3"},
{id: "4",title: "abc4"}];

moveElement(arr, "2","4");

5
请不要只发布代码作为答案,还要提供解释您的代码是如何解决问题的以及它的工作原理。附带解释的答案通常更有帮助、质量更高,并且更有可能获得赞同。 - Mark Rotteveel

-2

使用ES6,可以这样做...

想象一下你有这2个数组...

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]

-3
如果只需要交换第一个和最后一个元素:
array.unshift( array.pop() );

1
这段代码有缺陷。它将数组的最后一个元素移至开头,这并不是一种交换。 这段代码执行的结果是 [1, 2, 3] => [3, 1, 2] 而不是 [1, 2, 3] => [3, 2, 1] - David Archibald

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接