parseInt
·
1 min read
Today I saw a parseInt question on our company’s internal platform, and the result was surprising. The root cause was unclear understanding of parseInt execution, so I’m documenting it here.
Problem
parseInt('0xf',16)
// 15
parseInt('0xf')
// 15
parseInt(0xf,16)
// 21
parseInt(15,16)
// 21
Explanation
- The first parameter of parseInt starts from the first non-whitespace character. For non-string values, it performs ToString conversion, so parseInt(15,16) is essentially parseInt(‘15’,16).
- parseInt(‘0xf’,16) - JavaScript recognizes the string as a hexadecimal number, and the radix is also hexadecimal, so it directly parses to 15. parseInt(‘0xf’) doesn’t pass a radix, but based on the 0x prefix in the string, it’s still recognized as hexadecimal, so it’s still 15.
Interview Question
Understanding the processing logic, let’s analyze this code:
['1', '2', '3'].map(parseInt)
The callback logic for the above program is as follows:
parseInt(1,0); // 1
parseInt(2,1); // NaN
parseInt(3,2); // NaN
radix 0 is equivalent to base 10. radix 1 results in NaN. Base 2 cannot have 3, so it results in NaN.
Personally, I don’t think memorizing these processing logic has much value. The real valuable points are:
- Pay attention to automatic type conversion - there are many such issues in JavaScript.
- Be careful with callback writing like map(parseInt) to avoid accidentally passing the index and causing unexpected results.