Handling Radix in Array#map parseInt Calls
In the context of JavaScript arrays, the map method transforms each element using a provided callback function. While map can successfully apply Math.sqrt on numbers, its behavior with parseInt on strings can be confusing.
One might expect ['1', '2', '3'].map(parseInt) to return [1, 2, 3]. However, it actually yields [1, NaN, NaN]. This oddity stems from parseInt's radix parameter.
The Role of Radix in parseInt
parseInt expects two arguments: the value to be converted and the radix. If the radix is omitted, it uses the "best guess" based on the input.
In the case of ['1', '2', '3'].map(parseInt), the radix becomes the index of each element during the array iteration. Thus, it ends up calling:
1 2 3 |
|
Resolving the Issue
To resolve this issue and obtain the desired result [1, 2, 3], you can use a wrapper function like this:
1 |
|
or with ES2015 syntax:
1 |
|
Here, the radix is explicitly set to 10, ensuring correct parsing.
The above is the detailed content of Why Does `['1', '2', '3'].map(parseInt)` Return `[1, NaN, NaN]` in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!