Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
121
rated 0 times [  126] [ 5]  / answers: 1 / hits: 36861  / 8 Years ago, tue, november 22, 2016, 12:00:00

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!


More From » javascript

 Answers
4

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]));




[#59957] Monday, November 21, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
leilanichasel

Total Points: 224
Total Questions: 112
Total Answers: 94

Location: Angola
Member since Wed, Apr 13, 2022
2 Years ago
;