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
相关文档:
今天在做一个学生信息修改页面的时候遇到了一点小问题,因需求指出学生在查看个人信息时可以申告其中的错误信息,并提交正确信息,所以我在显示基本信息的时候对于学院、专业和班级等就采用了下拉菜单,为了使下拉菜单显示学生当前的信息,且具有联动效果需在js中获取session中传过来的相 ......
/**
* 6 级强度设置(数字、大写字母、小写字母、特殊字符、长度>=6、长度>=10)
* 如果密码为空,返回 0
*/
function __pwdStrength(pwd) {
var sum = [0, 0, 0, 0];
for (var i=0; i<pwd.length; i++) {
& ......
<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 ......
JSP+JavaScrip
t打造二级级联下拉菜单:
(个人博客:www.duduct.com)
class(一级栏目信息):classId(自动编号),className(栏目名称),
Nclass(二级栏目信息),
NclassId(自动编号),NclassName(栏目名称),parentId(一级栏目id,与class表中的classId关联)
......