Definition and Usage
The parseInt() function parses a string and returns an integer.
The radix parameter is used to specify which numeral system to be used, for example, a radix of 16 (hexadecimal) indicates that the number in the string should be parsed from a hexadecimal number to a decimal number.
If the radix parameter is omitted, JavaScript assumes the following:
• If the string begins with "0x", the radix is 16 (hexadecimal)
• If the string begins with "0", the radix is 8 (octal). This feature is deprecated
• If the string begins with any other value, the radix is 10 (decimal)
Note: Only the first number in the string is returned!
Note: Leading and trailing spaces are allowed.
Note: If the first character cannot be converted to a number, parseInt() returns NaN.
Note: Older browsers will result parseInt("010") as 8, because older versions of ECMAScript, (older than ECMAScript 5, uses the octal radix (8) as default when the string begins with "0". As of ECMAScript 5, the default is the decimal radix (10).
大体翻译:
定义和用法:
parseInt函数解析字符串并返回一个整数。
第二个参数进制常用来说明根据哪个进制来进行转换,列如可以进行十六进制的转换。
如果第二个参数——进制没有定义,则会按照下面的规则进行转换:
如果字符串以0X开头,则按照16进制
如果字符串以0开头,则进行8进制转换
如果字符串以其他开头,则默认进行10进制转换
提示:
只有字符串的第一个数字被转换
字符串开头和结尾的空格是允许的,转换时被忽略
如果开头的第一个字符不能被转换成数字,就会立即返回NaN
较早的浏览器会将parseInt(010)按照8进制进行转换
开头的0或0.0之类的格式会被忽略直到查找到不为0的字符
Example
Parse different strings:
var a = parseInt("10") + "<br>";
var b = parseInt("10.00") + "<br>";
var c = parseInt("10.33") + "<br>";
var d = parseInt("34 45 66") + "<br>";
var e = parseInt(" 60 ") + "<br>";
var f = parseInt("40 years") + "<br>";
var g = parseInt("He was 40") + "<br>";
var h = parseInt("10",10)+ "<br>";
var i = parseInt("010")+ "<br>";
var j = parseInt("10",8)+ "<br>";
var k = parseInt("0x10")+ "<br>";
var l = parseInt("10",16)+ "<br>";
var n = a + b + c + d + e + f + g + "<br>" + h + i + j + k +l;
The result of n will be:
10
10
10
34
60
40
NaN
10
10
8
16
16