有人知道如何在JavaScript中检查变量是数字还是字符串吗?
当前回答
你正在寻找isNaN():
console.log(!isNaN(123)); console.log(!isNaN(-1.23)); console.log(!isNaN(5-2)); console.log(!isNaN(0)); console.log(!isNaN(“0”)); console.log(!isNaN(“2”)); console.log(!isNaN(“Hello”)); console.log(!isNaN(“2005/12/12”));
参见JavaScript isNaN()函数在MDN。
其他回答
最好的方法是使用isNaN +类型转换:
更新的all-in方法:
function isNumber(n) { return !isNaN(parseFloat(n)) && !isNaN(n - 0) }
使用regex也一样:
function isNumber(n) { return /^-?[\d.]+(?:e-?\d+)?$/.test(n); }
------------------------
isNumber('123'); // true
isNumber('123abc'); // false
isNumber(5); // true
isNumber('q345'); // false
isNumber(null); // false
isNumber(undefined); // false
isNumber(false); // false
isNumber(' '); // false
//testing data types accurately in JavaScript (opposed to "typeof")
//from http://bonsaiden.github.com/JavaScript-Garden/
function is(type, obj) {
var clas = Object.prototype.toString.call(obj).slice(8, -1);
return obj !== undefined && obj !== null && clas === type;
}
//basic usage
is('String', 'test'); // true
is('Array', true); // false
或者调整它以返回未知类型:
function realTypeOf(obj) {
return Object.prototype.toString.call(obj).slice(8, -1);
}
//usage
realTypeOf(999); // 'Number'
2012年5月12日更新: Javascript的完整例子:A Better typeof。
或者只使用isNaN()的倒数:
if(!isNaN(data))
do something with the number
else
it is a string
是的,使用jQuery的$. isnumeric()更有趣。
效率测试
我知道我该怎么用…
isNaN(parseFloat(n)) && !isNaN(n - 0)} 函数isNumberRE (n){返回/ ^ - ? (\ d。)+ (?:e - ? \ d +) ?美元/ test (n);} function test(fn, timerLabel) { console.time (timerLabel) For (i = 0;I < 1000000;我+ +){ const num = Math.random() * 100 const isNum = fn(num) } console.timeEnd (timerLabel) } test(isNumber, "Normal way") test(isNumberRE, "RegEx方式")
Normal way: 25.103271484375 ms
RegEx way: 334.791015625 ms
jQuery使用这个:
function isNumber(obj) {
return !isNaN( parseFloat( obj ) ) && isFinite( obj );
}