@Joel's answer is pretty close, but it will fail in the following cases:
(@Joel的答案非常接近,但在以下情况下将失败:)
// Whitespace strings:
IsNumeric(' ') == true;
IsNumeric('') == true;
IsNumeric('
') == true;
// Number literals:
IsNumeric(-1) == false;
IsNumeric(0) == false;
IsNumeric(1.1) == false;
IsNumeric(8e5) == false;
Some time ago I had to implement an IsNumeric
function, to find out if a variable contained a numeric value, regardless of its type , it could be a String
containing a numeric value (I had to consider also exponential notation, etc.), a Number
object, virtually anything could be passed to that function, I couldn't make any type assumptions, taking care of type coercion (eg. +true == 1;
but true
shouldn't be considered as "numeric"
).
(前一段时间,我必须实现一个IsNumeric
函数,以查明一个变量是否包含数值, 而不论其类型如何 ,它可能是一个包含数值的String
(我还必须考虑指数表示法,等等), Number
对象,几乎任何东西都可以传递给该函数,我不能做任何类型假设,要注意类型强制(例如+true == 1;
但是true
不应被视为"numeric"
)。)
I think is worth sharing this set of +30 unit tests made to numerous function implementations, and also share the one that passes all my tests:
(我认为值得分享针对多种功能实现进行的这套+30单元测试 ,还应该分享通过我所有测试的测试:)
function isNumeric(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
PS isNaN & isFinite have a confusing behavior due to forced conversion to number.
(由于强制转换为数字,因此PS isNaN和isFinite的行为令人困惑。)
In ES6, Number.isNaN & Number.isFinite would fix these issues.(在ES6中, Number.isNaN和Number.isFinite将解决这些问题。)
Keep that in mind when using them.(使用它们时请记住这一点。)
Update : Here's how jQuery does it now (2.2-stable) :
(更新 : 这是jQuery现在的方式(2.2稳定) :)
isNumeric: function(obj) {
var realStringObj = obj && obj.toString();
return !jQuery.isArray(obj) && (realStringObj - parseFloat(realStringObj) + 1) >= 0;
}
Update : Angular 4.3 :
(更新 : Angular 4.3 :)
export function isNumeric(value: any): boolean {
return !isNaN(value - parseFloat(value));
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…