易截截图软件、单文件、免安装、纯绿色、仅160KB

javascript parseInt is broken

javascript parseInt is broken
I was debugging some strange errors in a date conversion function I was writing, and I stumbled upon something that amazed me... a strange bug in parseInt
>>>parseInt('06')
6
>>>parseInt('07')
7
>>>parseInt('08')
0
>>>parseInt('09')
0
>>>parseFloat('08')
8
>>>parseFloat('09')
9
 
Clearly for the strings '08' and '09' parseInt fails to return the right value. One workaround is easy, use parseFloat.
Why does this happen and where should I report this? I find it extremely odd that it happens in both Firefox and Internet Explorer 6 & 7; there must be some explanation right?
You can test it out for yourself using the FireBug javascript console), or by using one of these two links
alert(parseInt('07')+' == 7 ?')
alert(parseInt('08')+' == 8 ?')
Ok, Ok, so now that I explained how you would expect it to work (and clearly how I expected it to work) I'm going to answer my own question (yes I hate it when I do that too)
The problem is with how parseInt guesses the base of your number. Read the parseInt spec. Instead of always defaulting to base 10, it tries to guess, and if the first character is '0' it thinks you want to parse as an octal number, and if it starts with '0x' it thinks you want hexadecimal.
So, the solution is either to use parseFloat or to always specify your base.
Defaults that change on their own can't be trusted.
>>>parseInt('08',10)
8
 


相关文档:

[JAVASCRIPT] this 对象

看了很多javascrip代码,发现很多地方用到了this这个对象,那这个到底是什么东西阿?
先让我们来理解一个概念:
在javascript会有一个上下文的概念,任何一个对象无论是Object 还是function 都会有一个专有的上下文对象,也可以理解为它自己的拥有者。
那么我们很容易想到这个拥有者,必然有个终点,那就是window对象。 ......

javascript中的null和undefined

javascript中的null和undefined
本文装载网络,版权归原作者所有。
null :表示无值;
undefined : 表示一个未声明的变量,
                或已声明但没有赋值的变量,
          &nb ......

IE和Firefox之间的JavaScript差异

尽管 JavaScript 历史上使用冗长而令人生厌的代码块来标的特定浏览器的时期已经结束了,但是偶尔使用一些简单的代码块和对象检测来确保一些代码在用户机器上正常工作依然是必要的。
    这篇文章中,我会略述一下 Internet Explorer 和 Firefox 在 JavaScript 语法上不同的几 个方面。
    ......

JavaScript类型判断

在JavaScript中,变量中可以存储的值主要有两种类型:原始值(primitive value)和引用值(reference value)。前者通常是固定而又简单的数据,存储在栈(stack)中,而后者则是比较大的对象,存储在堆(heap)中,而对于后者的调用,是通过存储在栈中的指针来完成的。原始类型有五种:Number、String、Boolean、Null和Unde ......

JSP+JavaScript打造二级级联下拉菜单

JSP+JavaScrip
t打造二级级联下拉菜单:
(个人博客:www.duduct.com)
class(一级栏目信息):classId(自动编号),className(栏目名称),
Nclass(二级栏目信息),
NclassId(自动编号),NclassName(栏目名称),parentId(一级栏目id,与class表中的classId关联)
......
© 2009 ej38.com All Rights Reserved. 关于E健网联系我们 | 站点地图 | 赣ICP备09004571号