Home > Web Front-end > JS Tutorial > Why Does `parseInt` Return `NaN` When Used with `Array#map`?

Why Does `parseInt` Return `NaN` When Used with `Array#map`?

DDD
Release: 2024-12-14 15:02:12
Original
664 people have browsed it

Why Does `parseInt` Return `NaN` When Used with `Array#map`?

Why Does parseInt Return NaN with Array#map?

The Mozilla Developer Network states that [1,4,9].map(Math.sqrt) returns [1,2,3]. However, applying parseInt to the array literal ['1','2','3'] with map yields [1, NaN, NaN]. This behavior occurs in Firefox 3.0.1 and Chrome 0.3.

The Root Cause

The discrepancy arises from the callback function in map having three parameters: the element's value, its index, and the traversed array object. When parseInt is called within map, the index becomes the second argument, which it interprets as the radix (the base of the number system being converted).

In the aforementioned case, parseInt is called with radix values of 0, 1, and 2, respectively. The radix is 10 by default for integers without a leading zero. However, radix 1 is invalid, and radix 2 does not support the number 3. Hence, parseInt returns NaN for the second and third elements.

The Solution

To rectify this, a wrapper function can be utilized:

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

Alternatively, in ES2015 :

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

By explicitly providing the radix as 10, we ensure that parseInt correctly interprets the strings as base-10 integers.

The above is the detailed content of Why Does `parseInt` Return `NaN` When Used with `Array#map`?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template