Home >Web Front-end >JS Tutorial >Why Does `Array.map()` with `parseInt()` Produce Unexpected Results in JavaScript?

Why Does `Array.map()` with `parseInt()` Produce Unexpected Results in JavaScript?

Susan Sarandon
Susan SarandonOriginal
2024-12-17 11:10:27161browse

Why Does `Array.map()` with `parseInt()` Produce Unexpected Results in JavaScript?

Parsing Numbers in Array.map() with parseInt

In Javascript, the Array.map() function applies a callback function to each element of an array. However, the parseInt() function, when used in this context, can yield unexpected results.

In the provided example:

['1','2','3'].map(parseInt);

parseInt() yields [1, NaN, NaN] instead of the expected [1, 2, 3]. This behavior arises because parseInt() takes two arguments: the string to parse and an optional radix (base).

The Array.map() callback function provides three parameters: the element value, its index, and the array itself. When using parseInt() without specifying a radix, it uses the second parameter (the index) as the radix.

For ['1','2','3'], the radix values used by parseInt() become 0, 1, and 2. Since radix 1 is invalid and 3 is not representable in binary (radix 2), the parsing fails, resulting in NaN.

To correct this behavior, provide an explicit radix to parseInt() within a wrapper function:

['1','2','3'].map(function(num) { return parseInt(num, 10); });

Alternatively, use the ES2015 syntax:

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

By specifying a radix of 10, we ensure that parseInt() correctly parses the strings into integers.

The above is the detailed content of Why Does `Array.map()` with `parseInt()` Produce Unexpected Results in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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