Ò׽ؽØÍ¼Èí¼þ¡¢µ¥Îļþ¡¢Ãâ°²×°¡¢´¿ÂÌÉ«¡¢½ö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
 


Ïà¹ØÎĵµ£º

C#ºǫ́µ÷ÓÃǰ̨javascriptµÄÎåÖÖ·½·¨


ÓÉÓÚÏîÄ¿ÐèÒª£¬Óõ½ÆäËûÏîÄ¿×éÓÃVC¿ª·¢µÄ×é¼þ£¬ÔÚwebºǫ́´úÂëÎÞ·¨·ÃÎÊÕâ¸ö×é¼þ£¬ËùÒÔÖ»ºÃͨ¹ýºǫ́µ÷ÓÃǰ̨µÄjavascript£¬´Ó¶ø²Ù×÷Õâ¸ö×é¼þ¡£ÔÚÍøÉÏÕÒÁËÕÒ£¬·¢ÏÖÓÐÈýÖÖ·½·¨¿ÉÒÔ·ÃÎʵ½Ç°Ì¨´úÂ룺
µÚÒ»ÖÖ£¬OnClientClick    (vs2003²»Ö§³ÖÕâ¸ö·½·¨)
<asp:Button ID="Button1" runat="se ......

JavaScript̰³ÔÉß

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head><title>̰ʳÉß</title></head>
<body>
<mce:style type="text/css"><!--
.tab ......

flex ºÍjavascript»¥Ïàµ÷ÓÃ

flex ºÍjavascript»¥Ïàµ÷Óá£
Ò»¡¢flex µ÷ÓÃjavascript
  Ö»ÐèʹÓþ²Ì¬µÄExternalInterface.call¾Í¿ÉÒÔÁË¡£
  call ·½·¨ÖÁÉÙÒªÇóÒ»¸ö²ÎÊý£¬¾ÍËùµ÷ÓöÊýµÄÃû³Æ¡£
  Ò²¿ÉÒÔ´«µÝ²ÎÊý¡£
  È磺
    ExternalInterface.call("alert","hello");
   "hello"¾ÍÊÇ×÷Ϊalertµ ......

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ºÅ