且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

parseInt()和parseFloat()之间的行为差​​异

更新时间:2022-11-13 14:44:44

parseInt()根据字符串中的第一个字符假定您的号码的基数。如果它以 0x 开头,则假定为16(十六进制)。否则,如果它以 0 开头,则假定为8(八进制)。否则它假设基数为10。

parseInt() assumes the base of your number according to the first characters in the string. If it begins with 0x it assumes base 16 (hexadecimal). Otherwise, if it begins with 0 it assumes base 8 (octal). Otherwise it assumes base 10.

您可以将基数指定为第二个参数:

You can specify the base as a second argument:

alert(parseInt(hfrom[0], 10)); // 8

来自MDN(上面链接):

From MDN (linked above):


如果radix未定义或为0,则JavaScript假定以下内容:

If radix is undefined or 0, JavaScript assumes the following:

如果输入字符串以0x或0X开头,基数是16
(十六进制)。如果输入字符串以0开头,则基数为8
(八进制)。这个功能是非标准的,有些实现
故意不支持它(而是使用基数10)。对于这个
的原因,在使用parseInt时总是指定一个基数。如果输入字符串
以任何其他值开头,则基数为10(十进制)。

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).