Javascript parseInt给出了非常意外的结果 [英] Javascript parseInt gives very unexpected results
问题描述
我'解析一个字符串以检查它是否是一个日期,我们现在发现我的方法不适用于八月或九月的日期。这就是我所做的(输入不是真的硬编码,显然,但为了简洁......):
I'm parsing a string to check if it's a date, and by chance we now discovered that my method doesn't work for dates in august or september. This is what I do (the input isn't really hard-coded, obviously, but for brevity...):
var str = '2010-08-26 14:53';
var data = str.split(' '); // ['2010-08-26', '14:53']
var date = data[0].split('-'); // ['2010', '08', '26]
var time = data[1].split(':'); // ['14', '53']
var yyyy = parseInt(date[0]); // 2010
// THIS IS WHERE STRANGE THINGS HAPPEN:
var MM = parseInt(date[1]); // 0 - not 08 or 8, as expected!
console.log(date[1]); // prints "08" (with quotes)
console.log(date[1].toString()); // prints 08 (no quotes)
console.log(parseInt(date[1].toString())); // prints 0 (!)
此问题出现在8月和9月,以及8日和9日每个月 - 也就是说,当08
或09
被解析为整数时,<$ c返回$ c> 0 而不是 8
或 9
。该代码适用于较低(例如07
)和更高(例如10
)整数(至少在预期的日期范围内...)
This problem arises for august and september, and for the 8th and 9th every month - that is, when either "08"
or "09"
is being parsed to integer, 0
is returned instead of 8
or 9
. The code works for both lower (e.g. "07"
) and higher (e.g. "10"
) integers (at least within expected date ranges...)
我做错了什么?
推荐答案
使用
parseInt(date[1], 10)
以确保字符串被解释为基数10(十进制)。
to make sure the string is interpreted as base 10 (decimal).
否则,它是如果它以0
开头,则解释为基数8(八进制),如果以0x开头,则解释为基数16(十六进制)
。
Otherwise, it is interpreted as base 8 (octal) if it starts with "0"
, or as base 16 (hexadecimal) if it starts with "0x"
.
实际上,你应该总是包含基本参数以避免这些类型的错误。
In fact, you should always include the base argument to avoid these kinds of bugs.
这篇关于Javascript parseInt给出了非常意外的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!