Hi JavaScript masters !
console.log([ '5', '9', '7' ].map(parseInt))
tells me [5, NaN, NaN]
console.log([ '5', '9', '7' ].map(function(element){
return parseInt(element)
}))
tells me [5, 9, 7]
But why ? ^^'
Hi JavaScript masters !
console.log([ '5', '9', '7' ].map(parseInt))
tells me [5, NaN, NaN]
console.log([ '5', '9', '7' ].map(function(element){
return parseInt(element)
}))
tells me [5, 9, 7]
But why ? ^^'
This happens because, as it is described here:
parseInt is often used with one argument, but takes two. The first is an expression and the second is 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.
map
calls the function you give it with 3 parameters: the value, the index of it in the array, and the array itself. Your second approach safely ignores these, but your first one causes the second parameter to be interpreted as the base of the number, which isn't what you wanted.
Best explained here: https://stackoverflow.com/a/262511/6935763
No use of copying pasting here the whole answer