zoukankan      html  css  js  c++  java
  • 关于"parseInt"

    在进行js脚本编写的时候,parseInt这个函数经常被使用,
    目的是将 一个字符串转换为整型数.但是这个函数的实现和我们一般的想象有一定的差距.如:

    我们用 parseInt('08'),希望得到的是 8,结果得到的是 0  (特别是在日期转换中)

    在js帮助中有这样一段:
    parseInt( ) parses and returns the first number (with an optional leading minus sign) that occurs in s. Parsing stops, and the value is returned, when parseInt( ) encounters a character in s that is not a valid digit for the specified radix. If s does not begin with a number that parseInt( ) can parse, the function returns the not-a-number value NaN. Use the isNaN( ) function to test for this return value.

    The radix argument specifies the base of the number to be parsed. Specifying 10 makes parseInt( ) parse a decimal number. The value 8 specifies that an octal number (using digits 0 through 7) is to be parsed. The value 16 specifies a hexadecimal value, using digits 0 through 9 and letters A through F. radix can be any value between 2 and 36.

    If radix is 0 or is not specified, parseInt( ) TRies to determine the radix of the number from s. If s begins (after an optional minus sign) with 0x, parseInt( ) parses the remainder of s as a hexadecimal number. If s begins with a 0, the ECMAScript v3 standard allows an implementation of parseInt( ) to interpret the following characters as an octal number or as a decimal number. Otherwise, if s begins with a digit from 1 through 9, parseInt( ) parses it as a decimal number.


    所以 parseInt对于 0开头的字符串,且不是0x,当作了八进制进行处理,碰到8,就当作是非法字符中断了处理,所以结果就是0.

    因此,在日期处理上,只有碰到 08,09,才会出现问题,所以大多数人很难不查文档很难发觉.

    那应该怎么办呢?其实js提供了一个重载函数来解决这个问题
    parseInt(s, radix)

    radix

    An optional integer argument that represents the radix (i.e., base) of the number to be parsed. If this argument is omitted or is 0, the number is parsed in base 10or in base 16 if it begins with 0x or 0X. If this argument is less than 2 or greater than 36, parseInt( ) returns NaN.

    我们可以用 parseInt( '08',10)进行转换就没有问题了. 

  • 相关阅读:
    网上购物瘾,你怎么能退出?
    POJ 1006 Biorhythms 中国的法律来解决剩余的正式
    【Android接口实现】PhotoView——单点支持/多图像缩放,实现了触摸
    线程同步synchronized
    阿里云CentOS 6.5 设备、执行Docker容器和步骤的方法
    打破了中国电信华为无线路由猫(HG522-C)自己主动拨号+任意数量的计算机+iTV
    GCC 命令行具体解释
    Nginx 负载均衡
    Linux pipe功能
    Java有用的经验--Swing片
  • 原文地址:https://www.cnblogs.com/superch0054/p/4010166.html
Copyright © 2011-2022 走看看