Definition and usage analysis of parseInt of function in javascript

  • 2020-05-07 19:14:30
  • OfStack

This article illustrates the definition and usage of the parseInt() function in javascript. Share with you for your reference. Specific analysis is as follows:

This function parses 1 string and returns 1 integer.

syntax structure:

parseInt(string, type)

Parameter list:

参数 描述
string 必需。要被解析的字符串。
type 可选。表示要解析的数字的基数,通俗的说就是数字的进制,比如2进制、8进制或者106进制。该值介于2 ~ 36之间。

:

1. Specify type parameters:

After specifying the type parameter, the function parses the string with the type parameter specified, for example:
1.parseInt("010",10), which means "010" is in base 10 and the return value is 10.
2.parseInt("010",2), which means that "010" is in base 2 and the return value is 2.
3.parseInt("010",8), which means "010" is in base 8 and the return value is 8.
4.parseInt("010",16), which means "010" is in base 106 and returns a value of 16.
Note: the return values are all in base 10. type says that the specified value is the base of the first parameter, and the return value of the second parameter is between 2-36. If not, the return value of the parseInt function is NaN. The parseInt function returns only the number before the first character if the string parameter is not all Numbers but other characters. Such as:
parseInt("123ab789",10) returns a value of 123, with the first character a omitted altogether.

2. type parameter is not specified:

When the type parameter is not specified, the parseInt function automatically determines which base is used, which is usually in decimal, for example:

1.parseInt("23") returns 23.
2.parseInt("23ab") returns 23.

But it's not always that simple. Here's another example:

The return value of parseInt("0x12") is 18, which is not the number before the first string is returned. This is the case here. If the string begins with "0x", be careful, because the number after "0x" is considered to be in base 106, so the return value is 18. If it starts with "0" and is not immediately followed by a character, it will be parsed in base 10 in Google, but in base 8 in IE. Such as:
parseInt (" 0123 ") returns 123 in the Google browser and 83 in the IE browser.

I hope this article is helpful for your javascript programming.


Related articles: