How can I reverse an array in JavaScript without using libraries?

前端 未结 30 1003

I am saving some data in order using arrays, and I want to add a function that the user can reverse the list. I can\'t think of any possible method, so if anybo

相关标签:
30条回答
  • 2020-11-27 06:13

    What about without using push() !

    Solution using XOR !

    var myARray = [1,2,3,4,5,6,7,8];
    
    function rver(x){
        var l = x.length;
        for(var i=0; i<Math.floor(l/2); i++){
    
            var a = x[i];
            var b = x[l-1-i];
    
            a = a^b;
            b = b^a;
            a = a^b;
    
            x[i] = a;
            x[l-1-i] = b;
        }
    
        return x;
    
    }
    
    console.log(rver(myARray));
    
    0 讨论(0)
  • 2020-11-27 06:14
    > var arr = [1,2,3,4,5,6];
    > arr.reverse();
      [6, 5, 4, 3, 2, 1]
    
    0 讨论(0)
  • 2020-11-27 06:15

    This is what you want:

    array.reverse();
    

    DEMO

    0 讨论(0)
  • 2020-11-27 06:15

    Pure functions to reverse an array using functional programming:

    var a = [3,5,7,8];
    
    // ES2015
    function immutableReverse(arr) {
      return [ ...a ].reverse();
    }
    
    // ES5
    function immutableReverse(arr) {
      return a.concat().reverse()
    }
    
    0 讨论(0)
  • 2020-11-27 06:16
    function reverseArray(arr) {
        let reversed = [];
        for (i = 0; i < arr.length; i++) { 
        reversed.push((arr[arr.length-1-i]))
        }
      return reversed;
    }
    
    0 讨论(0)
  • 2020-11-27 06:19

    **

    Shortest reverse array method without using reverse method:

    **

     var a = [0, 1, 4, 1, 3, 9, 3, 7, 8544, 4, 2, 1, 2, 3];
    
     a.map(a.pop,[...a]); 
    // returns [3, 2, 1, 2, 4, 8544, 7, 3, 9, 3, 1, 4, 1, 0]
    

    a.pop method takes an last element off and puts upfront with spread operator ()

    MDN links for reference:

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/pop

    0 讨论(0)
提交回复
热议问题