当前位置: 首页 > 网络学院 > 客户端脚本教程 > JavaScript > JavaScript parseInt() 方法

JavaScript
JS 字符串
JS Date
JS数组,JS Array
JS Boolean
JS Math
JS HTML DOM
JS Browser
JS Cookies
JS 校验
JS Animation
JS Image Maps
JS Timing
JS 建立对象
JS 摘要
JS 实例
JS 对象实例
JS DOM 实例
JS数组对象参考
JS布尔对象参考
JS日期对象参考

JavaScript parseInt() 方法


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-03-04   浏览: 394 ::
收藏到网摘: n/a

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


Try-It-Yourself Demos
互动演练

parseInt()
How to use parseInt() to parse different strings.
如何用parseInt()方法来转换不同的字符串

评论 (0) All

登陆 | 还没注册?