有人知道如何在JavaScript中检查变量是数字还是字符串吗?
当前回答
聚会很晚才来;然而,当我想一次性检查某些输入是字符串还是数字时,下面的方法总是很有效。
return !!Object.prototype.toString.call(input).match(/\[object (String|Number)\]/);
其他回答
试试这个,
<script>
var regInteger = /^-?\d+$/;
function isInteger( str ) {
return regInteger.test( str );
}
if(isInteger("1a11")) {
console.log( 'Integer' );
} else {
console.log( 'Non Integer' );
}
</script>
最好的方法是使用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
创建了一个jsperf,用于检查变量是否为数字。很有趣!Typeof实际上有一个性能用途。对于数字以外的任何东西使用typeof,通常以速度的1/3作为变量。构造函数,因为javascript中的大多数数据类型都是对象;数字不是!
http://jsperf.com/jemiloii-fastest-method-to-check-if-type-is-a-number
Typeof变量=== 'number'|最快|如果你想要一个数字,比如5,而不是'5' typeof parseFloat(variable) === 'number'|最快|如果你想要一个数字,比如5,和'5'
isNaN()比较慢,但也没慢那么多。我对parseInt和parseFloat寄予厚望,但它们的速度慢得可怕。
对于数字检测,以下文章来自Douglas Crockford的JavaScript: the Good Parts:
isFinite函数是确定一个值是否可以用作数字的最佳方法,因为它拒绝NaN和Infinity。不幸的是,isFinite将尝试将其操作数转换为一个数字,因此如果一个值实际上不是一个数字,那么它不是一个好的测试。你可能想要定义自己的isNumber函数:
var isNumber = function isNumber(value) { return typeof value === 'number' &&
isFinite(value);
};
//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。