Home > Web Front-end > JS Tutorial > body text

JavaScript中的ParseInt("08")和“09”返回0的原因分析及解决办法_javascript技巧

WBOY
Release: 2016-05-23 13:15:47
Original
1066 people have browsed it

今天在程序中出现一个bugger ,调试了好久,最后才发现,原来是这个问题。

做了一个实验:

alert(parseInt("01")),当这个里面的值为01====》07时都是正常的,但是在"08","09"就会返回0

(这种现象出现在ie内核的浏览器中,如360浏览器就会出现这种错误)(谷歌,火狐不受影响)

查阅资料得知着这种现象原因:

大神的解释:

01--07自然没有问题,但是09,08都是不合格的八进制形式,所以被按照0处理了。为了解决这个问题,可以利用parseInt函数的另一个参数,显示的告诉parseInt按照十进制处理。

parseInt("08",10) 或者 parseInt("09",10)

parseInt(string,radix)的作用是将string转换为整数,第二个参数是设置string的格式,常用的有2、8、10、16,表示string是多少进制的数。

radix 可取值的范围是2~36,如果不在这个范围内,将返回NaN。

如果设置radix的值是0或者不设置时,会自动识别string的格式:

以 "0x" 开头,parseInt() 会把 string 除0x外的其余部分当作十六进制数,

以 "0" 开头,parseInt() 会把 string 除0外的字符当作八进制或十六进制数,

以 1 ~ 9 的数字开头,parseInt() 将把它当作十进制数。

以上所述是小编给大家介绍的JavaScript中ParseInt("08")和“09”返回0的原因分析及解决办法的相关知识,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对脚本之家网站的支持!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!