javascript的parseInt()详解

本文详细介绍了JavaScript中的parseInt()函数,包括其如何解析字符串并返回整数值、不同情况下默认的进制选择规则,以及一些重要的使用注意事项。

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函数解析字符串并返回一个整数。
第二个参数进制常用来说明根据哪个进制来进行转换,列如可以进行十六进制的转换。
如果第二个参数——进制没有定义,则会按照下面的规则进行转换:

  1. 如果字符串以0X开头,则按照16进制

  2. 如果字符串以0开头,则进行8进制转换

  3. 如果字符串以其他开头,则默认进行10进制转换

提示:

  1. 只有字符串的第一个数字被转换

  2. 字符串开头和结尾的空格是允许的,转换时被忽略

  3. 如果开头的第一个字符不能被转换成数字,就会立即返回NaN

  4. 较早的浏览器会将parseInt(010)按照8进制进行转换

  5. 开头的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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值