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中的null和undefined
本文装载网络,版权归原作者所有。
null :表示无值;
undefined : 表示一个未声明的变量,
或已声明但没有赋值的变量,
&nb ......
今天在做一个学生信息修改页面的时候遇到了一点小问题,因需求指出学生在查看个人信息时可以申告其中的错误信息,并提交正确信息,所以我在显示基本信息的时候对于学院、专业和班级等就采用了下拉菜单,为了使下拉菜单显示学生当前的信息,且具有联动效果需在js中获取session中传过来的相 ......
通过分析各类浏览器的userAgent信息,不难得出分辨各类浏览器及其版本的正则表达式。而且,对浏览器类型的判断和版本的判断完全可以合为一体地进行。于是,我们可以写出下面的代码:
<script type="text/javascript">
  ......
以下全是个人理解以及网上查找而来,如有不对请指正...
假如有n段js代码 用<script>标签隔开的.
运行顺序是
step1. 读入第一个代码段
step2. 做语法分析,有错则报语法错误(比如括号不匹配等),并跳转到step5
step3. 对var变量和function定义做“预解析”(永远不会报错的,因为只解析正确的声明)
......
<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 ......