6

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.

rid
  • 61,078
  • 31
  • 152
  • 193
Yaw Boakye
  • 10,352
  • 1
  • 17
  • 25
  • 6
    explained at https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/map – John Dvorak May 18 '13 at 09:20
  • also simple fix: `numbers.map( function(i) { return parseInt(i) })` – Jonah May 18 '13 at 09:24
  • Also, don't forget to *always* pass the radix parameter to `parseInt()` and set it to `10` if you're using base 10, because, otherwise, you're likely to encounter strange and very hard to debug issues later on. – rid May 18 '13 at 09:40

2 Answers2

4

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)

John Dvorak
  • 26,799
  • 13
  • 69
  • 83
Yuriy
  • 428
  • 3
  • 6
0

https://developer.mozilla.org/en-GB/docs/JavaScript/Reference/Global_Objects/Array/map explains how map works.

I find it easier with the solution that jonah proposed, create a returning function for thing you want to map instead of tossing it..

intN = numbers.map(function(i) { return parseInt(i) });

The real reason is that you are trying to feed a function to map, but JS is not getting the function properly.

You better declare the function first and then feed it.

var titi = function(i) { return parseInt(i); };

var intN2 = numbers.map(titi);
Juan Vilar
  • 435
  • 3
  • 11