Reputation: 1
I am now practicing some methods in javascript, like shift(), unshift(), push(), pop()
, and I want to write a little function that will take 3 arguments, an array, a start point, an end point. Which is used to cut a part of array out, and then return both the new array and the cut part. Not a useful thing or a big deal, just want to practice javascript.
But I encountered a strange thing, which I don't know why.
Here is the strange part
var a1 = [];
var a2 = [9,8,7,6,5,4,3,2,1];
for(var i=0; i<a2.length; i++){
a1.unshift(a2.shift())
}
So I wrote this code, and the expected result should be
a1 = [1,2,4,5,6,7,8,9]
a2 = []
However, when I run the code, this was what actually happened
a1 = [5,6,7,8,9]
a2 = [4,3,2,1]
It seems like the function was looped not enough time, so I tried to change the a2.length to a integer: 9
which make the code become
var a1 = [];
var a2 = [9,8,7,6,5,4,3,2,1];
for(var i=0; i<9; i++){
a1.unshift(a2.shift())
}
And that worked!
Then I change the approach to this
var a1 = [];
var a2 = [9,8,7,6,5,4,3,2,1]
var aLength = a2.length;
for(var i=0; i<aLength; i++){
a1.unshift(a2.shift())
}
And this worked too!!!
Could anyone tell me why is that ??? And how can I improve the loop?
Thank you very much, really appreciate for your time.
Upvotes: 0
Views: 76
Reputation: 904
You could easily do this by using while loop
while (a2.length > 0)
{
a1.unshift(a2.shift());
}
Upvotes: 1
Reputation: 1993
Javascript Array: Shift() Method
The shift() method is like the pop() method, only it works at the beginning of the array. The shift() method pulls the first element off of the given array and returns it. This alters the array on which the method was called.
So when you do a a2.shift() it will actually modify (decrease the number of elements in the array) the array and thus the effect
Upvotes: 0
Reputation: 385104
The loop condition is re-evaluated for each iteration, and a2.length
is constantly changing.
If you want to use its initial value, cache it beforehand:
var n = a2.length;
for (var i = 0; i < n; i++) {
a1.unshift(a2.shift());
}
Upvotes: 0