srishti sharma - 1 year ago 47

Javascript Question

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++)`

{

arr.push(parseInt(arr[i]));

arr.shift();

}

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++){

arr.push(parseInt(arr[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.

Answer Source

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"`