首页 > 代码库 > JavaScript Patterns 2.8 Number Conversions with parseInt()
JavaScript Patterns 2.8 Number Conversions with parseInt()
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 8 Number("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.
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。