What's wrong with my reverse array code?

This is my code:

function reverseArray(array){
  var newArray = [];
  for (i = 0; i <= array.length + 1; i++)
    newArray.unshift(array.shift());
  return newArray;
};

      

I don't understand why the condition is not in the for loop i < array.length

. For example, when an array has 3 elements, it seems to me that you would need to loop through the array 3 times, moving each element into a new array, but for some reason on consoles when I try it (for example console.log(reverseArray(["a", "b", "c"]))

), I had to change it to the current i <= array.length + 1;

one to get the code to give the correct output ["c", "b", "a"]

. I don't understand why, if someone can help explain why it i < array.length

doesn't work, I would really appreciate it. Thank!

+3


source to share


2 answers


  • your code is an error in checking the if condition because every time the condition is checked in the for statement, so array.lenght changes every time and the condition should not be array.length + 1, you can try below code

    function reverseArray(array){
      var newArray = [];
      for (var i = 0,len=array.length; i < len; i++)
        newArray.unshift(array.shift());
      return newArray;
    };
    
          

  • I suggest using the reverse array method, but if you want to create a new copy of the array you can use Array.slice (), try this:

    function reverseArray(array){
        var newArray=array.slice()
        newArray.reverse()
        return newArray
    }
    
          



+2


source


For some reason, if you cannot use Array.prototype.reverse

, I would write a function like this

function reverseArray(arr) {
  var len = arr.length;
  var rev = new Array(len);
  for (var i=0, j=len-1; i<len; i++, j--) {
    rev[i] = arr[j];
  }
  return rev;
}

reverseArray([1,2,3]);
// [3,2,1]

      



You can see this decision to dominate in tests . It's even faster than native Array.prototype.reverse

using a 10 element array (tested in Chrome).

+1


source







All Articles