+ 9
JavaScript Map
Why does this code returns. (1, NaN, 3) let x = ["1", "7", "11"].map(parseInt) console.log(x)
3 Answers
+ 2
parseInt takes 2 arguments and the array.map callback takes 3, (value, index, array). parseInt's second argument is the base it should parse, and if it is 0, it finds the base (eg. 0x... is base 16, and a normal number is base 10).
Knowing this, this is how it would execute:
parseInt(value, index)
parseInt("1", 0) -> 1 (parsed as decimal since it isn't prefixed with something to show a different base)
parseInt("7", 1) -> NaN (base 1 always seems to return NaN since it's not a valid base)
parseInt("11", 2) -> 3 (11 from binary to decimal)
+ 1
probably sth with binary.
since
1b = 1d
11b = 3d
7 is not binary and cannot be converted so it becomes NaN
+ 1
Actually parseInt can take one argument. Radix parameter is optional. The thing is you missed calback in map method, so add lambda function:
["1","7","11"].map(o => parseInt(o))