Reputation: 2055
I run following code and javascript return crazy resualt?
code:
"000000000000000000000000".split('').map(parseInt)
output:
[0, NaN, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
why second item of array is NaN?
Upvotes: 0
Views: 45
Reputation: 1405
parseInt
actually takes two arguments, the second one being the radix; map
will provide three arguments to the called function: the current value, the current index, and the whole array.
This means that the first item will be parsetInt(0, 0)
, the second one parseInt(0, 1)
and so on...
You should force the arguments count:
"000000000000000000000000".split('').map(function(n) { return parseInt(n); })
Upvotes: 3
Reputation: 3171
map calls the function with three parameters. The first is the element, the second is the index in the array (the third is the array itself). parseInt takes two arguments.
It's cleary explained here:
http://www.quora.com/Exactly-why-does-10-10-10-10-10-map-parseInt-return-10-NaN-2-3-4-in-JavaScript
Upvotes: 2