We have an array:

var mass = ["elem1", "elem2", "elem3", "elem4" "elem5"]; 

What is the easiest way to swap 2 and 4 (for example, an element)? In addition to reassignment through an additional type variable

 temp1 = mass[2]; mass[2] = mass[4]; mass[4] = temp1; 

Maybe in Js there is a more elegant way? (well, like the .SORT function for sorting) Or is this the only way?

    3 answers 3

    In modern js, there is such a method, called destructuring assignment:

     [mass[1], mass[3]] = [mass[3], mass[1]]; 

    I.e

     [a, b] = [b, a]; 

    That's just IE11 and Androids do not know how out of the box , if you want to write so that it works everywhere, you will have to translate.

    There is still a working-class "ninja" way for which, in a decent society, they are kicking for non-readability:

     mass[1] = [mass[3], mass[3] = mass[1]][0]; 

    I.e:

     a = [b, b = a][0]; 
    • Excellent explained. Thank. - Typography Manager

    here is another old working "nijia" for array correction

     var arr = [2,1,3,5,4,0] arr[1] = arr.splice(0,1, arr[1])[0] //console.log(arr) 

    arrays can be corrected through a method, for understanding by providing the code with comments.

     function correctArr(_arr, _param){ /* коррСкция элСмСнтов массива ΠΏΠΎ ΠΏΠ°Ρ€Π΅ индСкса * _arr -- массив Ρ‚Ρ€Π΅Π±ΡƒΡŽΡ‰ΠΈΠΉ ΠΊΠΎΡ€Ρ€Π΅ΠΊΡ†ΠΈΠΈ * _param -- ΠΏΠ°Ρ€Π° [n1,n2] -- индСксы массива для Π²Π·Π°ΠΈΠΌΠ½ΠΎΠΉ пСрСстановки */ _arr[_param[1]] = _arr.splice(_param[0],1, _arr[_param[1]])[0] } //correctArr(arr, [1,0]) //console.log(arr.toString()) 

    You can write a method with a loop with function reference, and returning a new array.

     function corrects_Arr(){ var _param, _arr = arguments[0].slice(), _arguments = Array.prototype.slice.call(arguments, 1) for(var i = 0; i < _arguments.length; i++){ correctArr(_arr, _arguments[i]) } return _arr } /* console.log( arr.toString() +" "+ "инспСктируСмый массив остался ΠΏΡ€Π΅ΠΆΠ½ΠΈΠΌ" +"\n"+ corrects_Arr(arr, [0,1], [4,3]).toString() +" "+ "Π²Π΅Ρ€Π½ΡƒΠ»ΠΈ скоррСктированный массив" ) */ 

    for simplicity of future handling of arrays, it is possible to weight the solution of the problem, by assigning the prototype Array constructor to its own method, which can be called on all arrays.

     Array.prototype["myCorrects"] = function(_param){ if(_param){ this[_param[1]] = this.splice(_param[0],1, this[_param[1]])[0] this.constructor.prototype.myCorrects.apply(this, Array.prototype.slice.call(arguments, 1)) } return this } arr = arr.myCorrects([0,1], [3,4]).splice(-1,1).concat(arr) console.log(arr.toString()) 

       var arr = [1, 2, 3, 4, 5, 6, 7, 8]; for (var res = [], j = arr.length - 1; j >= 0; j -= 4) res.unshift (arr [j - 2]), res.unshift (arr [j - 3]), res.unshift (arr [j]), res.unshift (arr [j - 1]); alert (res); 

      • 6
        Let's loop up the entire array to swap two variables. P - performance. - Duck Learns to Take Cover
      • How does the creation of a new array answer the question? - vp_arth