Home > Web Front-end > JS Tutorial > Why Does `['1', '2', '3'].map(parseInt)` Return `[1, NaN, NaN]` in JavaScript?

Why Does `['1', '2', '3'].map(parseInt)` Return `[1, NaN, NaN]` in JavaScript?

Barbara Streisand
Release: 2024-12-27 21:00:19
Original
185 people have browsed it

Why Does `['1', '2', '3'].map(parseInt)` Return `[1, NaN, NaN]` in JavaScript?

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
Copy after login

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); });
Copy after login

or with ES2015 syntax:

['1', '2', '3'].map(num => parseInt(num, 10));
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template