Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is 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 in the for loop the condition isn't i < array.length. For example, when the array has 3 elements, it seems to me that you would need to loop over the array 3 times, shifting each element into the new array, but for some reason on the 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; to get the code to give the correct output ["c", "b", "a"]. I do not understand why, if someone could help explain why i < array.length doesn't work I would really appreciate it. Thanks!

like image 588
ben432rew Avatar asked Jul 12 '26 07:07

ben432rew


1 Answers

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

    function reverseArray(array){
      var newArray = [];
      for (var i = 0,len=array.length; i < len; i++)
        newArray.unshift(array.shift());
      return newArray;
    };
    
  2. I suggest to use the reverse method of the Array, but if you want to make a new copy of the array, you can use Array.slice(), try this:

    function reverseArray(array){
        var newArray=array.slice()
        newArray.reverse()
        return newArray
    }
    
like image 55
powerfj Avatar answered Jul 14 '26 20:07

powerfj



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!