<分区>
为什么 parseInt()
和 parseFloat()
之间存在这种行为差异?
我有一个包含 08
的字符串。
当我写这段代码时:
alert(hfrom[0]);
alert(parseInt(hfrom[0]));
alert(parseFloat(hfrom[0]));
生成以下输出:
08
0
8
为什么在这种情况下 parseInt
和 parseFloat
返回两个不同的结果?
<分区>
为什么 parseInt()
和 parseFloat()
之间存在这种行为差异?
我有一个包含 08
的字符串。
当我写这段代码时:
alert(hfrom[0]);
alert(parseInt(hfrom[0]));
alert(parseFloat(hfrom[0]));
生成以下输出:
08
0
8
为什么在这种情况下 parseInt
和 parseFloat
返回两个不同的结果?
最佳答案
parseInt()根据字符串中的第一个字符假定您的数字的基数。如果它以 0x
开头,它假定以 16 为底(十六进制)。否则,如果它以 0
开头,则假定基数为 8(八进制)。否则它假定基数为 10。
您可以将基数指定为第二个参数:
alert(parseInt(hfrom[0], 10)); // 8
来自 MDN(上面链接):
If radix is undefined or 0, JavaScript assumes the following:
If the input string begins with "0x" or "0X", radix is 16 (hexadecimal). If the input string begins with "0", radix is eight (octal). This feature is non-standard, and some implementations deliberately do not support it (instead using the radix 10). For this reason always specify a radix when using parseInt. If the input string begins with any other value, the radix is 10 (decimal).
关于javascript - parseInt() 和 parseFloat() 之间的行为差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9528433/