The examples in this article describe the definition and usage of the parseInt() function in JavaScript. Share it with everyone for your reference. The specific analysis is as follows:
This function can parse a string and return an integer.
Grammar structure:
Parameter list:
Parameters | Description
|
||||||
string | Required. The string to be parsed.
|
||||||
type | Optional. Indicates the base of the number to be parsed, which in layman's terms is the base of the number, such as binary, octal or hexadecimal. The value is between 2 ~ 36. |
1. Specify type parameter:
After specifying the type parameter, the function will parse the string according to the specified type parameter, for example:
1.parseInt("010",10), which means "010" is decimal, and the return value is 10.
2.parseInt("010",2), which means "010" is binary, and the return value is 2.
3.parseInt("010",8), which means "010" is octal, and the return value is 8.
4.parseInt("010",16), which means "010" is hexadecimal and the return value is 16.
Note: The return values are all decimal. The type specifies the base of the first parameter, and the return value of the second parameter is between 2-36. If it is not in this range, the return value of the parseInt function is NaN. If the string parameters are not all numbers, but contain other characters, the parseInt function only returns the numbers before the first character. For example:
2. Do not specify the type parameter:
When the type parameter is not specified, the parseInt function will automatically determine which base it is, which is usually decimal, for example:
1.parseInt("23") The return value is 23.
But the situation is often not as simple as above. Let’s look at an example:
The return value of parseInt("0x12") is 18, which is not the number before returning the first string. There is a situation here. If the string starts with "0x", you should pay attention to it, because this At this time, the number after "0x" will be considered as hexadecimal, so the return value is 18. If it starts with "0" and is not followed by a character, then at this time, it will be parsed in decimal under Google Chrome, but it will be parsed in octal under IE browser. For example:
I hope this article will be helpful to everyone’s JavaScript programming design.