打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
JavaScript parseInt() 方法

Definition and Usage
定义与用法

The parseInt() function parses a string and returns an integer.
parseInt()方法用于将一个字符串转换为整型数字。

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.
进制参数用于指定目标字符串的进制类型。如:设定进制为16,目标字符串将从16进制先转为10进制再进行处理。

If the radix parameter is omitted, JavaScript assumes the following:
如果没有指定进制参数,JavaScript将依照下列规则进行:

  • If the string begins with "0x", the radix is 16 (hexadecimal)
    如果字符串以"0x"开始,视为16进制
  • If the string begins with "0", the radix is 8 (octal). This feature is deprecated
    如果字符串以"0"开始,视为8进制
  • If the string begins with any other value, the radix is 10 (decimal)
    其他的视为10进制

Syntax
语法

parseInt(string, radix)

Parameter
参数
Description
注释
string
字符串
Required. The string to be parsed
必选项。所要转换的字符串
radix
进制
Optional. A number (from 2 to 36) that represents the numeral system to be used
可选项。2到36,指定字符串的进制类型


Tips and Notes
注意

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.
注意:如果字符串的第一个字符不能被转换成数字,将返回NaN


Example
实例

In this example we will use parseInt() to parse different strings:
在下面的例子中,我们演示了如何用parseInt()方法来转换不同的字符串:

<script type="text/javascript">
document.write(parseInt("10") + "<br />") 
document.write(parseInt("10.00") + "<br />")
document.write(parseInt("10.33") + "<br />")
document.write(parseInt("34 45 66") + "<br />")
document.write(parseInt(" 60 ") + "<br />")
document.write(parseInt("40 years") + "<br />")
document.write(parseInt("He was 40") + "<br />")

document.write("<br />")

document.write(parseInt("10")+ "<br />")
document.write(parseInt("10",10)+ "<br />")

document.write(parseInt("010")+ "<br />")
document.write(parseInt("10",8)+ "<br />")

document.write(parseInt("0x10")+ "<br />")
document.write(parseInt("10",16)+ "<br />")
</script>

The output of the code above will be:
输出结果为:

10
10
10
34
60
40
NaN
10
10
8
8
16
16
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
JavaScript?二、八、十、十六进制转换方法 -网站开发-技术中心-启天网
JavaScript的系统函数学习
前端教程:JavascriptString.substring()方法
解惑 [“1”, "2", "3"].map(parseInt) 为何返回[1,NaN,NaN]
JavaScript|日期对象
JavaScript使用手册
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服