首页 > 网站 > WEB开发 > 正文

JavaScript Patterns 2.8 Number Conversions with parseInt()

2024-04-27 14:23:42
字体:
来源:转载
供稿:网友

javaScript Patterns 2.8 Number Conversions with parseInt()

2014-05-23 12:28 by 小郝(Kaibo Hao), ... 阅读, ... 评论, 收藏, 编辑

Strings that start with 0 are treated as octal numbers (base 8) in ECMAScript 3; however, this has changed in ES5. To avoid inconsistency and unexpected results, always specify the radix parameter:

var month = "06",year = "09";month = parseInt(month, 10);year = parseInt(year, 10);

Alternative ways to convert a string to a number include:

+"08" // result is 8Number("08") // 8

These are often faster than parseInt(), because parseInt(), as the name suggests, parses and doesn't simply convert. But if you're expecting input such as "08 hello", parseInt() will return a number, whereas the others will fail with NaN.


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表