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); });
Alternatively, in ES2015 :
['1','2','3'].map(num => parseInt(num, 10));
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!