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
相关文档:
由于项目需要,用到其他项目组用VC开发的组件,在web后台代码无法访问这个组件,所以只好通过后台调用前台的javascript,从而操作这个组件。在网上找了找,发现有三种方法可以访问到前台代码:
第一种,OnClientClick (vs2003不支持这个方法)
<asp:Button ID="Button1" runat="se ......
JavaScript过滤数组中重复元素
我是个JS初学者,我即将要说的这个方法也是大部分人都能想到的:
从旧数组中取元素,一个个添加到新数组中,在添加的时候,与添加过的元素比较,如果相同,则不添加。
首先定义两个数组:
Code
var arrA = new Array(1,23,43,64,1,23,5,8,3,5,9);
var arrB&n ......
在JavaScript中,变量中可以存储的值主要有两种类型:原始值(primitive value)和引用值(reference value)。前者通常是固定而又简单的数据,存储在栈(stack)中,而后者则是比较大的对象,存储在堆(heap)中,而对于后者的调用,是通过存储在栈中的指针来完成的。原始类型有五种:Number、String、Boolean、Null和Unde ......
在面向对象编程语言中,对于this关键字我们是非常熟悉的。比如C++、C#和Java等都提供了这个关 键字,虽然在开始学习的时候觉得比较难,但只要理解了,用起来是非常方便和意义确定的。JavaScript也提供了这个this关键字,不过用起来就比 经典OO语言中要"混乱"的多了。
下面就来看看,在JavaScript中各种 ......
JSP+JavaScrip
t打造二级级联下拉菜单:
(个人博客:www.duduct.com)
class(一级栏目信息):classId(自动编号),className(栏目名称),
Nclass(二级栏目信息),
NclassId(自动编号),NclassName(栏目名称),parentId(一级栏目id,与class表中的classId关联)
......