Reputation: 1902
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!
Upvotes: 3
Views: 205
Reputation: 77778
For whatever reason, if you can't use Array.prototype.reverse
, I would write the 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 solution dominate the benchmarks. It's even faster than the native Array.prototype.reverse
using a 10-element array (tested in Chrome).
Upvotes: 1
Reputation: 156
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;
};
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
}
Upvotes: 2