['1', '2', '3'].map(parseInt) returns [1, NaN, NaN]
['1', '2', '3'].map(parseInt) returns [1, NaN, NaN] in JavaScript means map() passes each item's index as a second argument, and parseInt treats its second argument as the radix (number base).
How do I fix ['1', '2', '3'].map(parseInt) returns [1, NaN, NaN]?
In JavaScript, ['1', '2', '3'].map(parseInt) returns [1, NaN, NaN] because map() passes the index as a second argument, and parseInt reads it as the number base. parseInt("2", 1) is NaN. Wrap the call so only the value is passed: arr.map((s) => parseInt(s, 10)), or use arr.map(Number).
- 1. Functions passed to mapLook for .map(parseInt) or any function with an optional second parameter passed straight to map().
- 2. Always give a radixCall parseInt(s, 10) so the base is fixed at 10.
- 3. Need decimals?parseInt drops fractions. Use Number(s) or parseFloat(s) for values like "1.5".
What does ['1', '2', '3'].map(parseInt) returns [1, NaN, NaN] mean?
map calls parseInt("1", 0), parseInt("2", 1), parseInt("3", 2). Radix 0 means "guess" (10), radix 1 is invalid (NaN), and "3" is not a binary digit (NaN). Any function with an optional second parameter can misbehave when passed straight to map.
Why does ['1', '2', '3'].map(parseInt) returns [1, NaN, NaN] happen?
1. Passing parseInt directly to map
The index becomes the base.
Breaks
["10", "10", "10"].map(parseInt) // [10, NaN, 2]Works
["10", "10", "10"].map((s) => parseInt(s, 10)) // [10, 10, 10]2. Wanting decimals
parseInt drops the fraction.
Breaks
["1.5", "2.5"].map((s) => parseInt(s, 10)) // [1, 2]Works
["1.5", "2.5"].map(Number) // [1.5, 2.5]How to find it in your own code
Wrap the function so it receives only the value: arr.map((s) => parseInt(s, 10)), or use arr.map(Number), which takes a single argument.
Try it: fix this bug
mediumparseAll(["10", "10", "10"]) returns [10, NaN, 2].
function parseAll(strings) {
return strings.map(parseInt);
}Still not sure why yours breaks?
Paste it into the visualizer and watch it run line by line, with every variable at every step. Free, and it runs in your browser.