Home  >  Q&A  >  body text

javascript - How to swap the positions of two elements in a js array?

Is there an easy way? Please give me more advice!

怪我咯怪我咯2712 days ago641

reply all(7)I'll reply

  • 天蓬老师

    天蓬老师2017-05-18 11:02:40

    The easiest thing to think of is

      ` var temp = arr[i];
            arr[i] = arr[j];
            arr[j] = temp;`    或者就是利用字符串和数组的一些方法进行交换,上面也有人提到了。 

    reply
    0
  • 过去多啦不再A梦

    过去多啦不再A梦2017-05-18 11:02:40

    arr[i]=[arr[j], arr[j]=arr[i]][0]

    reply
    0
  • 某草草

    某草草2017-05-18 11:02:40

    ES6 can be as simple as
    [a,b] = [b,a]

    reply
    0
  • 仅有的幸福

    仅有的幸福2017-05-18 11:02:40

    // 给你来个最经典的冒泡排序算法
    var arr = [1,3,5,7,9,8,6,4,2];
    for (let i = 0; i < arr.length; i++) {
        for (let j = i; j < arr.length; j++) {
            if (arr[i] < arr[j]) {
                // 后面这三行是调换位置的方法
                var temp = arr[i];
                arr[i] = arr[j];
                arr[j] = temp;
            }
        }
    }
    console.log(arr);

    reply
    0
  • 滿天的星座

    滿天的星座2017-05-18 11:02:40

    Isn’t it easy enough to use tmp? Then try this

    let a=[1,2,3];
    [a[1], a[2]]=[a[2], a[1]];

    reply
    0
  • 習慣沉默

    習慣沉默2017-05-18 11:02:40

    var a = [1,4,6,43,5,9,0,23,45];

        function change(arr,k,j) {
            var c = arr[k];
    
            arr[k] = arr[j];
            arr[j] = c;
            console.log(arr);
        }
    
        console.log(a);
        change(a,3,7);

    reply
    0
  • PHP中文网

    PHP中文网2017-05-18 11:02:40

    let arr = [1, 2, 3, 4, 5]
    // 交换第三个和第四个元素
    // x < y
    let x = 3, y = 4
    
    arr.splice(x - 1, 1, ...arr.splice(y - 1, 1, arr[x - 1]))
    console.log(arr) /// [1,2,4,3,5]

    reply
    0
  • Cancelreply