Reputation: 11
I want to reverse an array that I input into a function.
But for some reason the console returns the first value of the array instead of taking the full array within the while loop so it can unshift the value at the end to the front then delete that same value.
function littleWHEW(lemonade) {
let i = lemonade.length - 1;
while (i >= 0) {
lemonade.unshift(lemonade[i])
lemonade.pop(lemonade[i])
i = i - 1
}
return lemonade
}
console.info(littleWHEW([1,2,3,4,5]))
Upvotes: 0
Views: 83
Reputation: 94
Since you asked for explanation, let's take a deep investigation. Before we do, please take a look at
unshift
and pop
Firstly i = 4
. Here're what happens in one loop:
[1,2,3,4,5]
is the original array. lemonade.unshift(lemonade[i])
adds one element to the first position of lemonade
. At this point i = 4
so lemonade[4] = 5
, we have [5,1,2,3,4,5]
(notice the bold).pop
the last one out. [5,1,2,3,4,5]
becomes [5,1,2,3,4]
.i
.Now i = 3
, And here're what happens in second loop:
[5,1,2,3,4]
is the original array. lemonade.unshift(lemonade[i])
adds one element to the first position of lemonade
. At this point i = 3
so lemonade[3] = 3
, we have [3,5,1,2,3,4]
(notice the bold).pop
the last one out. [3,5,1,2,3,4]
becomes [3,5,1,2,3]
.i
.After one loop, your i
does not point to the last element as expected, and makes things wrong (as second loop does).
Upvotes: 0
Reputation: 1259
Just use the
reverse()
method:
function littleWHEW(lemonade) {
return lemonade.reverse();
}
You should not add a parameter to the pop() method, by the way.
Upvotes: 1