I want to reverse an array without using reverse() function like this:
function reverse(array){
var output = [];
for (var i = 0; i<= array.length; i++){
output.push(array.pop());
}
return output;
}
console.log(reverse([1,2,3,4,5,6,7]));
However, the it shows [7, 6, 5, 4] Can someone tell me, why my reverse function is wrong? Thanks in advance!
function reverse(array){ var output = []; for (var i = 0; i<= array. length; i++){ output. push(array. pop()); } return output; } console.
To reverse an array without modifying the original, call the slice() method on the array to create a shallow copy and call the reverse() method on the copy, e.g. arr. slice(). reverse() . The reverse method will not modify the original array when used on the copy.
JavaScript Array reverse()The reverse() method reverses the order of the elements in an array. The reverse() method overwrites the original array.
array.pop()
removes the popped element from the array, reducing its size by one. Once you're at i === 4
, your break condition no longer evaluates to true
and the loop ends.
One possible solution:
function reverse(array) {
var output = [];
while (array.length) {
output.push(array.pop());
}
return output;
}
console.log(reverse([1, 2, 3, 4, 5, 6, 7]));
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