11

Given the following:

> '10.0.0.1'.split('.').map(parseInt)
[10, NaN, 0, 1]

Why isn't the output instead:

[10, 0, 0, 1]

Despite the following holding true:

> x = '10.0.0.1'.split('.');
["10", "0", "0", "1"]

> x[1] == x[2]
true

Alternatively using parseFloat does give me the desired output; however I feel I am missing something crucial here.

EDIT: '10.0.0.1'.split('.').map(function(x) { return parseInt(x); }) works as expected.

EDIT2: I am using the Chrome Version 26.0.1410.64, but this also occurs in my local copy of node.js.

hiddensunset4
  • 5,825
  • 3
  • 39
  • 61
  • 1
    http://stackoverflow.com/questions/262427/javascript-arraymap-and-parseint http://stackoverflow.com/questions/8594699/map-parseint-strange-results – Josh Lee Apr 23 '13 at 00:39

2 Answers2

12

Look at the bottom of this link, at the "Tricky Use Case" which explains the NaN

https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/map

It is common to use the callback with one argument (the element being traversed). Some functions are also commonly used with one argument. These habits may lead to confusing behaviors.

// Consider:
["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.
// See the blog post for more details

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

["1", "2", "3"].map(returnInt);
// Actual result is an array of numbers (as expected) [1, 2, 3]
basarat
  • 261,912
  • 58
  • 460
  • 511
Cody Caughlan
  • 32,456
  • 5
  • 63
  • 68
  • +1, for speed and accuracy ! – Gabriele Petrioli Apr 23 '13 at 00:40
  • Thanks! I knew it would be something like this, but wasn't sure the search criteria. – hiddensunset4 Apr 23 '13 at 00:41
  • Great answer +1. The example you gave is exactly what was stumping me! I was wondering why I was getting different results on Chrome vs Firefox but that's because the behaviour when the radix is undefined is implementation-dependent. I now have a broader appreciation for why the Mozilla doc say "always specify a radix when using `parseInt`" – xlm Dec 17 '14 at 14:16
2

Quick solution, use parseFloat:

'10.0.0.1'.split('.').map(parseFloat); //=> [10,0,0,1]

Why parseInt doesn't work as expected? Answer here: javascript - Array#map and parseInt

Community
  • 1
  • 1
elclanrs
  • 92,861
  • 21
  • 134
  • 171