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:
parseInt('1', 0); // Correct (radix defaults to 10) parseInt('2', 1); // Invalid radix (not a number base) parseInt('3', 2); // Invalid number in base 2
Resolving the Issue
To resolve this issue and obtain the desired result [1, 2, 3], you can use a wrapper function like this:
['1', '2', '3'].map(function(num) { return parseInt(num, 10); });
or with ES2015 syntax:
['1', '2', '3'].map(num => parseInt(num, 10));
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!