parseInt在IE和chrome中表现不同 [英] parseInt behaving different in IE and chrome

查看:201
本文介绍了parseInt在IE和chrome中表现不同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有parseInt函数。



用于输入010:

在IE中输出:8
在chrome和firefox中输出: 10



为099作为输入:

在IE中输出:0
在chrome和firefox中输出:99



有人可以帮助我理解浏览器中的这种不同的行为。
问题在IE中,它在Chrome和Firefox中按预期工作。

预先感谢。

解决方案

实际上,我认为IE会在这里正确地做事情。 parseInt 将以 0 开头的字符串视为八进制输入。

>

要解决这个问题,请指定基数(在这种情况下,您需要小数点 - 10 ):

  num = parseInt(str,10); 






* 正确的情况确实意味着传统上。规范已经发生了变化。
从技术上讲,一个以<$ c开头的字符串$ c> 0 可以被视为八进制或十进制,具体取决于实现者的奇想,其中decimal是现在首选
$ b


如果基数<未定义或0(或不存在),JavaScript会采用以下:
$ b


  • 如果输入 string 以0开头,则基数为8八进制)或10(十进制)。究竟选择哪个基数是依赖于实现的。 ECMAScript 5指定使用10(十进制),但并非所有浏览器都支持此功能。由于这个原因,总是在使用parseInt时指定一个基数



i have parseInt function.

for 010 as input :

output in IE : 8 output in chrome and firefox: 10

for 099 as input:

output in IE : 0 output in chrome and firefox: 99

Could someone plz help me understand this different behaviour in the browsers.. issue is in IE and it is working as expected in chrome and firefox.

Thanks in advance.

解决方案

Actually I would argue IE is doing things correctly* here . parseInt for a string starting with a 0 is treated as octal input.

To fix the problem, specify the base (in this case, you want decimal - 10):

num = parseInt(str, 10);


* In this case "correctly" really means "traditionally". The specification has actually changed. Technically, a string starting with 0 can be treated as either octal OR decimal, depending on the implementor's whim, where decimal is now preferred:

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

  • If the input string begins with "0", radix is eight (octal) or 10 (decimal). Exactly which radix is chosen is implementation-dependent. ECMAScript 5 specifies that 10 (decimal) is used, but not all browsers support this yet. For this reason always specify a radix when using parseInt.

这篇关于parseInt在IE和chrome中表现不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆