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

前端 未结 30 1174

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:27

    JavaScript already has reverse() method on Array, so you don't need to do that much!

    Imagine you have the array below:

    var arr = [1, 2, 3, 4, 5];
    

    Now simply just do this:

    arr.reverse();
    

    and you get this as the result:

    [5, 4, 3, 2, 1];
    

    But this basically change the original array, you can write a function and use it to return a new array instead, something like this:

    function reverse(arr) {
      var i = arr.length, reversed = [];
      while(i) {
        i--;
        reversed.push(arr[i]);
      }
      return reversed;
    }
    

    Or simply chaning JavaScript built-in methods for Array like this:

    function reverse(arr) {
      return arr.slice().reverse();
    }
    

    and you can call it like this:

    reverse(arr); //return [5, 4, 3, 2, 1];
    

    Just as mentioned, the main difference is in the second way, you don't touch the original array...

提交回复
热议问题