易截截图软件、单文件、免安装、纯绿色、仅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] this 对象

看了很多javascrip代码,发现很多地方用到了this这个对象,那这个到底是什么东西阿?
先让我们来理解一个概念:
在javascript会有一个上下文的概念,任何一个对象无论是Object 还是function 都会有一个专有的上下文对象,也可以理解为它自己的拥有者。
那么我们很容易想到这个拥有者,必然有个终点,那就是window对象。 ......

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


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

javascript 运行机制

以下全是个人理解以及网上查找而来,如有不对请指正...
假如有n段js代码 用<script>标签隔开的.
运行顺序是
step1. 读入第一个代码段
step2. 做语法分析,有错则报语法错误(比如括号不匹配等),并跳转到step5
step3. 对var变量和function定义做“预解析”(永远不会报错的,因为只解析正确的声明)
......

JavaScript过滤数组中重复元素

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

Javascript 密码强度设置 脚本

/**
 * 6 级强度设置(数字、大写字母、小写字母、特殊字符、长度>=6、长度>=10)
 * 如果密码为空,返回 0
 */
function __pwdStrength(pwd) {
    var sum = [0, 0, 0, 0];
    for (var i=0; i<pwd.length; i++) {
      & ......
© 2009 ej38.com All Rights Reserved. 关于E健网联系我们 | 站点地图 | 赣ICP备09004571号