易截截图软件、单文件、免安装、纯绿色、仅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的RegExp对象和String对象定义了使用正则表达式来执行强大的模式匹配和文本检索与替换函数的方法.
  在JavaScript中,正则表达式是由一个RegExp对象表示的.当然,可以使用一个RegExp()构造函数来创建RegExp对象,也可以用
JavaScript
1.2中的新添加的一个特殊语法 ......

C#后台调用前台javascript的五种方法


由于项目需要,用到其他项目组用VC开发的组件,在web后台代码无法访问这个组件,所以只好通过后台调用前台的javascript,从而操作这个组件。在网上找了找,发现有三种方法可以访问到前台代码:
第一种,OnClientClick    (vs2003不支持这个方法)
<asp:Button ID="Button1" runat="se ......

JavaScript排序算法

1、插入排序->直接插入法排序
function InsertSort(arr) { //插入排序->直接插入法排序
var st = new Date();
var temp, j;
for(var i=1; i<arr.length; i++) {
if((arr[i]) < (arr[i-1])) {
temp = arr[i];
j = i-1;
do {
arr[j+1] = arr[j];
j--;
}
whil ......

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 ......
© 2009 ej38.com All Rights Reserved. 关于E健网联系我们 | 站点地图 | 赣ICP备09004571号