有人知道如何在JavaScript中检查变量是数字还是字符串吗?
当前回答
我发现的最好的方法是检查字符串上的方法,即:
if (x.substring) {
// do string thing
} else{
// do other thing
}
或者如果你想对number属性做一些检查,
if (x.toFixed) {
// do number thing
} else {
// do other thing
}
这有点像“鸭子打字”,由你自己决定哪种方式最有意义。我没有足够的因果报应来评论,但typeof失败的盒装字符串和数字,即:
alert(typeof new String('Hello World'));
alert(typeof new Number(5));
将提醒“对象”。
其他回答
最好的方法是使用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
因为像'1234'这样带有typeof的字符串将显示'string',而相反的情况永远不会发生(typeof 123将始终是number),最好是使用简单的正则表达式/^\-?\d+$/.test(var)。或者更高级的浮点数、整数和负数匹配,/^[\-\+]?[\d]+\.?(\d+)?美元/ .test的重要方面是,如果var不是字符串,它不会抛出异常,值可以是任何东西。
var val, regex = /^[\-\+]?[\d]+\.?(\d+)?$/;
regex.test(val) // false
val = '1234';
regex.test(val) // true
val = '-213';
regex.test(val) // true
val = '-213.2312';
regex.test(val) // true
val = '+213.2312';
regex.test(val) // true
val = 123;
regex.test(val) // true
val = new Number(123);
regex.test(val) // true
val = new String('123');
regex.test(val) // true
val = '1234e';
regex.test(val) // false
val = {};
regex.test(val) // false
val = false;
regex.test(val) // false
regex.test(undefined) // false
regex.test(null) // false
regex.test(window) // false
regex.test(document) // false
如果您正在寻找真正的类型,那么typeof单独就可以了。
我认为将var转换为字符串会降低性能,至少在最新的浏览器中进行的测试显示了这一点。
如果你关心性能,我会用这个:
typeof str === "string" || str instanceof String
用于检查变量是否为字符串(即使您使用var str = new string ("foo"), str instanceof string将返回true)。
至于检查它是否是一个数字,我会选择本地:isNaN;函数。
仅供参考,如果你使用jQuery你有
$.isNumeric()
来处理这个问题。更多详情请访问http://api.jquery.com/jQuery.isNumeric/
//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。