Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array map and parseInt woes [duplicate]

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.

like image 430
deceleratedcaviar Avatar asked Apr 23 '13 00:04

deceleratedcaviar


2 Answers

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

like image 113
elclanrs Avatar answered Nov 09 '22 16:11

elclanrs


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]
like image 12
Cody Caughlan Avatar answered Nov 09 '22 17:11

Cody Caughlan