srishti sharma srishti sharma - 3 months ago 12x
Javascript Question

why shifting array with a push copies last value to second last element?

I was working on a code in which I needed to convert strings to numbers in an array. I tried this-

for(var i=0;i<arr.length;i++)

What turned out to be weird for me is that the values returned were correct but at the end of array, the values of last and second last element always turned out to be same(i.e. the expected value of the last element),whereas this worked perfectly fine-

l= arr.length;
for(var i=0;i<l;i++){
var temp=begin.splice(0,l);

I am curious that why the first method didn't work because according to me it should. Any kind of help would be great.


You change both the input and the index (i) you use to read from the input

Assuming you have the ["2016","09","12"] then on the first iteration i is 0 and you do your arr.push(parseInt(arr[i])); arr.shift() then the result is:

["09","12", 2016] and i is incremented to 1 so at the next step you read "12" instead of "09"