Why does parseInt(1/0, 19) return 18?
I've an annoying problem in JavaScript.
> parseInt(1 / 0, 19)
> 18
Why does parseInt return 18 ?
The result of 1/0 is Infinity .
parseInt treats its first argument as a string which means first of all Infinity.toString() is called, producing the string "Infinity" . So it works the same as if you asked it to convert "Infinity" in base 19 to decimal.
Here are the digits in base 19 along with their decimal values:
Base 19 Base 10 (decimal)
---------------------------
0 0
1 1
2 2
3 3
4 4
5 5
6 6
7 7
8 8
9 9
a 10
b 11
c 12
d 13
e 14
f 15
g 16
h 17
i 18
What happens next is that parseInt scans the input "Infinity" to find which part of it can be parsed and stops after accepting the first I (because n is not a valid digit in base 19).
Therefore it behaves as if you called parseInt("I", 19) , which converts to decimal 18 by the table above.
Here's the sequence of events:
1/0 evaluates to Infinity parseInt reads Infinity and happily notes that I is 18 in base 19 parseInt ignores the remainder of the string, since it can't be converted. Note that you'd get a result for any base >= 19 , but not for bases below that. For bases >= 24 , you'll get a larger result, as n becomes a valid digit at that point.
To add to the above answers:
parseInt is intended to parse strings into numbers (the clue is in the name). In your situation, you don't want to do any parsing at all since 1/0 is already a number, so it's a strange choice of function. If you have a number (which you do) and want to convert it to a particular base, you should use toString with a radix instead.
var num = 1 / 0;
var numInBase19 = num.toString(19); // returns the string "Infinity"
链接地址: http://www.djcxy.com/p/1310.html
上一篇: 标准的JSON API响应格式?
