Why does my function return only [3, 2,]. It should print out the element 1 as well?
function reverseArr(arr) {
var reverse = [];
for (var i = 0; i < arr.length; i++)
reverse.push(arr.pop());
return reverse;
}
console.log(reverseArr([1, 2, 3]));
Because you're modifying arr
with each iteration, arr.length
is changing. Try this instead:
function reverseArr(arr) {
var reverse = [], len = arr.length;
for (var i = 0; i < len; i++)
reverse.push(arr.pop());
return reverse;
}
Note, however, this will modify the original array, which is probably not what you intended. If you'd like to preserve the original array, use unshift
instead:
function reverseArr(arr) {
var reverse = [], len = arr.length;
for (var i = 0; i < len; i++)
reverse.unshift(arr[i]);
return reverse;
}
Alternatively, you can use a combination of slice
and reverse
to return a new, reversed copy of the input array without modifying the original:
function reverseArr(arr) {
return arr.slice().reverse();
}
The problem is that you're changing the length of the array as you pop off of it. So arr.length
starts at 3 then 2 then 1. Instead, you could do something like this:
function reverseArr(arr) {
var reverse = [];
while (arr.length) {
reverse.push(arr.pop());
}
return reverse;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With