• 关于"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)进行转换就没有问题了. 

  • 相关阅读:
    TensorFlow笔记-初识
    SMP、NUMA、MPP体系结构介绍
    Page Cache, the Affair Between Memory and Files.页面缓存-内存与文件的那些事
    How The Kernel Manages Your Memory.内核是如何管理内存的
    Anatomy of a Program in Memory.剖析程序的内存布局
    Cache: a place for concealment and safekeeping.Cache: 一个隐藏并保存数据的场所
    Memory Translation and Segmentation.内存地址转换与分段
    CPU Rings, Privilege, and Protection.CPU的运行环, 特权级与保护
    The Kernel Boot Process.内核引导过程
    How Computers Boot Up.计算机的引导过程
  • 原文地址:https://www.cnblogs.com/superch0054/p/4010166.html
Copyright © 2020-2023  润新知