易截截图软件、单文件、免安装、纯绿色、仅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 获取对象的高度和宽度详细说明

scrollHeight: 获取对象的滚动高度。
scrollLeft:设置或获取位于对象左边界和窗口中目前可见内容的最左端之间的距离
scrollTop:设置或获取位于对象最顶端和窗口中可见内容的最顶端之间的距离
scrollWidth:获取对象的滚动宽度
offsetHeight:获取对象相对于版面或由父坐标 offsetParent 属性指定的父坐标的高度
offsetL ......

[转]JavaScript中的正则表达式解析

正则表达式是一个描述字符模式的对象。
  JavaScript的RegExp对象和String对象定义了使用正则表达式来执行强大的模式匹配和文本检索与替换函数的方法.
  在JavaScript中,正则表达式是由一个RegExp对象表示的.当然,可以使用一个RegExp()构造函数来创建RegExp对象,也可以用
JavaScript
1.2中的新添加的一个特殊语法 ......

JavaScript 鼠标拖拽进行快速产品分类效果

代码示例
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>无标题文档</title>
</head>
<mce:style><!--
.man{ float:left; background:#9af; margin:3px; padding:3px; cursor:default}
--></mce:style>< ......

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 ......

javascript this详解(转)

在面向对象编程语言中,对于this关键字我们是非常熟悉的。比如C++、C#和Java等都提供了这个关 键字,虽然在开始学习的时候觉得比较难,但只要理解了,用起来是非常方便和意义确定的。JavaScript也提供了这个this关键字,不过用起来就比 经典OO语言中要"混乱"的多了。
    下面就来看看,在JavaScript中各种 ......
© 2009 ej38.com All Rights Reserved. 关于E健网联系我们 | 站点地图 | 赣ICP备09004571号