Javascript is a dynamically typed langauges. This feature causes for Arrays, Booleans, and other types to be converted to a numeric values depending on usage.
However this feature can cause headarches when trying to detect numbers.
For example, isNaN() detects if a value is a non-number. That’s what NaN stands for, “Not a number”.
So you might think that the opposite result from isNaN() would indicate if a value is a number.
// Works for most cases but not for strict comparisons.
var isNumber = function(val){
return !isNaN( val );
};
Example:
Note: Click the “result” tab to run the test cases in jsfiddle.net.
Solution:
So here’s a simple fix for isNaN and isNumber.
// isNaN2 returns a boolean for if a value is not a number or +-Infinity
var isNaN2 = (function (global) {
var _isNaN = global.isNaN;
return function (val) {
return _isNaN("" + val) || (typeof val === "object" && !(val || "").hasOwnProperty('push'));
};
}(this));
// isNumeric returns a boolean for if a value is a number or +-Infinity
var isNumeric = (function (global) {
var _isNaN = global.isNaN;
return function (val) {
return !_isNaN("" + val)&&(typeof val !== "object" || (val || "").hasOwnProperty('push'));
};
}(this));
isNaN vs isNaN2
Testcases for isNaN2 and isNumeric
*Update*
Well it turns out that jQuery has a better implementation. The only difference is that infinity is not a number, which is correct.
$.isNumeric = function( obj ){
return !isNaN( parseFloat( obj ) ) && isFinite( obj );
};
What REALLY is Data Science? Told by a Data Scientist - By Joma Tech
Writing perfect code is a challenging process. That's where code reviews come in to help…
"The Next Leap: How A.I. will change the 3D industry - Andrew Price - Blender"
"Captain Disillusion: World's Greatest Blenderer - Live at the Blender Conference 2018 - CaptainDisillusion"
My 5 Favorite Linux Shell Tricks for SPEEEEEED (and efficiency) - By tutoriaLinux > What's…