Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

parseInt misbehaves when passed as argument to a map call [duplicate]

Tags:

javascript

Why is this happening?

var numbers = [ '1', '2', '3', '4' ];
var intNumbers = numbers.map( parseInt ); // intNumbers = [1, NaN, NaN, NaN]
var fltNumbers = numbers.map( parseFloat ); // fltNumbers = [1, 2, 3, 4, 5 ]

But Array.prototype.map.call( numbers, parseInt ); returns [ 1, 2, 3, 4];. I'm running this code in Google Chrome 26.0.1410.65.

like image 247
Yaw Boakye Avatar asked May 18 '13 09:05

Yaw Boakye


1 Answers

The link to proper answer is given in comments, but i want to post it here :

["1", "2", "3"].map(parseInt);

While one could expect [1, 2, 3]

The actual result is [1, NaN, NaN]

parseInt is often used with one argument, but takes two. The second being the radix To the callback function, Array.prototype.map passes 3 arguments: the element, the index, the array

The third argument is ignored by parseInt, but not the second one, hence the possible confusion.

Quick fix

function returnInt(element){
   return parseInt(element,10);
}


["1", "2", "3"].map(returnInt);

Actual result is an array of numbers (as expected)

like image 52
Yuriy Avatar answered Nov 01 '22 17:11

Yuriy