为什么parseInt(“09”)返回0但parseInt(“07”)返回7? [英] Why does parseInt("09") return 0 but parseInt("07") return 7?
本文介绍了为什么parseInt(“09”)返回0但parseInt(“07”)返回7?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
为什么
parseInt("09")
返回 0
但是
parseInt("07")
返回 7
?
推荐答案
以 0
开头的字符串的基数可以是八进制(当未指定基数 - 并且取决于浏览器。)
The base for strings starting with 0
can be octal (when a radix is not specified - and depending on the browser).
您正在寻找:
parseInt("09", 10)
请参阅 parseInt
:
如果未定义基数或者0,JavaScript假设如下:
If radix is undefined or 0, JavaScript assumes the following:
- 如果输入字符串以0x或0X开头,则基数为16(十六进制) 。
- 如果输入字符串以0开头,则基数为8(八进制)。此功能是非标准的,有些实现故意不支持它(而是使用基数10)。因此,在使用parseInt时总是指定一个基数。
- 如果输入字符串以任何其他值开头,则基数为10(十进制)。
radix
可选参数(我的例子中的第二个)的注释说这个:
The comments for the radix
optional parameter (the second one in my example) says this:
虽然这个参数是可选的,但始终指定它可以消除读者的困惑并保证可预测的行为。
While this parameter is optional, always specify it to eliminate reader confusion and to guarantee predictable behavior.
这篇关于为什么parseInt(“09”)返回0但parseInt(“07”)返回7?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文