10
['1','2','3'].map(parseInt)

return [1, NaN, NaN]

I don't know why? In my opinion is like this:

['1','2','3'].map(function(i){return parseInt(i,10)})

return [1, 2, 3]

======================================================
and other
['1','2','3'].map(parseFloat)
return [1, 2, 3]

lemon郑
  • 690
  • 5
  • 15

2 Answers2

10

You can find answer from Mozilla developers site:

// 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


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

["1", "2", "3"].map(returnInt);
// Actual result is an array of numbers (as expected)

Read more

Also read great answer

Community
  • 1
  • 1
Farkhat Mikhalko
  • 3,565
  • 3
  • 23
  • 37
7

Check out this article: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

The callback function is specified as:

callback
Function that produces an element of the new Array, taking three arguments:
currentValue
The current element being processed in the array.
index
The index of the current element being processed in the array.
array
The array map was called upon.

Therefore your map() function expands into:

parseInt('1', 0, the_array) # 1
parseInt('2', 1, the_array) # NaN
parseInt('3', 2, the_array) # NaN