Understanding JavaScript Functions: parseint ()

Source: Internet
Author: User

When using the parseint () function a few days ago, you may not be able to give the answer at a time in case of some conversions. Simply study it to avoid thinking about it again in the future.

Definition

1. w3school:

The parseint () function parses a string and returns an integer.

Link: http://www.w3school.com.cn/js/jsref_parseInt.asp

Http://www.w3school.com.cn/js/pro_js_typeconversion.asp

2. Mozilla developers

Parses a string argument and returns an integer of the specified Radix or base.

Link: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/parseInt

The differences between browsers are worth noting.

Analysis

According to the official explanation above, parseint (String,Radix)

There are two methods to call a function:

1. Specify radix. This is also the recommended method. Unfortunately, I didn't do this before.

2. Do not specify Radix, that is, parseint (String). Although simple, there are many rules, which is the core of this article.

Parseint (string, Radix)

Radix indicates the conversion base, which is commonly referred to as binary, octal, decimal, and hexadecimal. The range is from 2 ~ 36, but when we call this method in JS, the conversion is basically based on 10.

If this parameter is smaller than 2 or greater than 36, parseint () returns Nan.

The detailed rules for applying the "string" parameter are as follows:

(The base number 10 is used as an example because the occurrence frequency is the highest in actual use. However, for the use of other bases, you still need to be clear about the conversion between different operating systems. This should be a key course in computer science. If you forget it, it will be "Uncomfortable" to use this method"):

1) if they are all letters, Nan is returned, for example:

 
<SCRIPT type = "text/JavaScript">Window. onload=FunctionTestparse () {alert (parseint ("ABC", 10));}</SCRIPT>

2) If none of them are letters, 123 is returned, for example:

 
<SCRIPT type = "text/JavaScript">Window. onload=FunctionTestparse () {alert (parseint (& Quot; 123 & quot;, 10));}</SCRIPT>

3) if both letters and numbers exist, for example:

<SCRIPT type = "text/JavaScript">Window. onload=FunctionTestparse () {alert (parseint ("1x2bc", 10); Alert (parseint ("Df2bc", 10));}</SCRIPT>

Parseint ("1x2bc", 10) returns: 1

Parseint ("df2bc", 10) returns: Nan

Two rules are involved:

3.1) if the parameter "string" starts with a number, convert all the numbers before the first letter appears (nnd, I always feel that the description is not in place ).

In the above example, the first letter that appears is 'x'. Take the previous digit string and only one digit is '1'. Then 1 is returned.

3.2) if the parameter "string" starts with a letter, Nan is directly returned (because the 10-digit letter is not a valid expression, what if radix is 16? The results can be run on your own .)

The above description is based on the explanation of ecmascript (officially translated, very powerful ):

The parseint () method first checks the character at the position 0 to determine whether it is a valid number. If not, the method returns Nan and does not continue to perform other operations. However, if the character is a valid number, this method will view the characters at position 1 and perform the same test. This process continues until a non-valid number is found. At this time, parseint () converts the string before this character into a number.

This section describes parseint (string, Radix). If there are any errors or omissions, please refer to our official comments and thank you for your reference.

Parseint (string)

When calling this function in this way, there will be many "Hidden Rules" because there is no specified Radix displayed"

Below are two references

W3school

When the ParameterRadixIf the value is 0, or this parameter is not set, parseint ()StringTo determine the base number of a number.

For example, ifStringStarting with "0x", parseint ()StringThe rest is parsed as a hexadecimal integer. IfStringStarting with 0, ecmascript V3 allows an implementation of parseint () to parse the subsequent charactersOctal or hexadecimal. IfStringTake 1 ~ Start with a number of 9, parseint () will resolve it to a decimal integer.

Mozilla developers

  • If the inputStringBegins with "0x" or "0x ",RadixIs 16 (hexadecimal) and the remainder of the string is parsed.
  • If the inputStringBegins with "0 ", RadixIs eight (octal) or 10 (decimal). Exactly which radix is chosen is implementation-dependent. ecmascript 5 specifies that 10 (decimal) is used, but not all browsers support this yet. For this reasonAlways specify a radix when usingParseint.
  • If the inputStringBegins with any other value, the radix is 10 (decimal ).

If the first character cannot be converted to a number,ParseintReturnsNan.

The following is an example of the above content.

1) if the parameter "string" starts with "0x" or "0x", the base number is 16 by default, that is, the string is parsed in hexadecimal notation.

 
<SCRIPT type = "text/JavaScript">Window. onload=FunctionTestparse () {alert (parseint ("0 xabcg"));}</SCRIPT>

Result: 2478,10 * 16² + 11*16 + 12*1

If it is parseint ("0 xgabcg"), what? The answer is Nan. As I have already said above, the letter that follows 0x is g, not a valid hexadecimal character. According to ecmascript's explanation, Nan is directly returned.

2) If the parameter "string" starts with "0", the default base is?

Obviously, the w3school and Mozilla statements are inconsistent. Let's test and see that ie10, chrome, and Firefox are the latest versions)

 
<SCRIPT type = "text/JavaScript">Window. onload=FunctionTestparse () {alert (parseint ("010"));}</SCRIPT>

The results are as follows: 10, 10, and 8; ie10 and chrome are parsed in decimal notation, and FF is parsed in octal notation.

It seems that there is no hexadecimal parsing. Is it true? Continue Verification

 
<SCRIPT type = "text/JavaScript">Window. onload=FunctionTestparse () {alert (parseint ("09"));}</SCRIPT>

 

The results are 9, 9, and 0 in sequence. ie10 and chrome are parsed in hexadecimal notation, and FF is parsed in hexadecimal notation (because 9 is not a valid representation of hexadecimal notation, therefore, only the first digit 0 is parsed and the result is 0 ).

The conclusion of the verification is obvious. The description above by the Mozilla developer seems to be correct.

I only have these three browsers on my computer, so I cannot know what results will be produced by other browsers. If any one of them verifies that they can be converted in hexadecimal format, please inform 3q

3) if the parameter "string" does not start with the above two types, it will be parsed in hexadecimal notation.

 
<SCRIPT type = "text/JavaScript">Window. onload=FunctionTestparse () {alert (parseint ("Fff"));}</SCRIPT>

Result returned: Nan. The first letter 'F' is not a valid representation in decimal format, and Nan is directly returned.

4)The rules of this call method also follow the rules in the parseint (string, Radix) section, that is, only valid characters are parsed., For example:

 
<SCRIPT type = "text/JavaScript">Window. onload=FunctionTestparse () {alert (parseint ("0xf1x"); Alert (parseint ("021x"));}</SCRIPT>

The results are as follows:

241 (ie, chrome, ff), valid characters: "f1", 15*16 + 1 = 241

21 (ie, Chrome) or 17 (ff), valid character is "21", 10 is equal to 21,8: 2*8 + 1 = 17

 

End

Parseint () is a simple function in JS, but it is because you do not pay much attention to these details that it is very "troublesome" to use ". I hope this chapter will help you.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.