易截截图软件、单文件、免安装、纯绿色、仅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过滤数组中重复元素

JavaScript过滤数组中重复元素
我是个JS初学者,我即将要说的这个方法也是大部分人都能想到的:
从旧数组中取元素,一个个添加到新数组中,在添加的时候,与添加过的元素比较,如果相同,则不添加。
首先定义两个数组:
Code
var arrA = new Array(1,23,43,64,1,23,5,8,3,5,9);
var arrB&n ......

JavaScript类型判断

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

Javascript实现日期时间的倒计时

<html>
<body>
<SCRIPT type="text/javascript">
<!--
var target=[]
var time_id=[]
function ShowDateTime(){
    setTimeout("ShowDateTime()", 1000);
for (var i=0,j=target.length;i<j;i++)
{
    var today=new Date();
    timeo ......

JavaScript 生成 table

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>test</title>
<mce:style type="text/css"><!--
.table_back{width:480px;height:480px;border-bottom:1px solid bla ......
© 2009 ej38.com All Rights Reserved. 关于E健网联系我们 | 站点地图 | 赣ICP备09004571号