有人知道如何在JavaScript中检查变量是数字还是字符串吗?
当前回答
简单地使用
myVar.constructor == String
or
myVar.constructor == Number
如果要处理定义为对象或字面量并保存的字符串,则不需要使用helper函数。
其他回答
我发现的最好的方法是检查字符串上的方法,即:
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));
将提醒“对象”。
如果你处理的是文字符号,而不是构造函数,你可以使用typeof:。
typeof "Hello World"; // string
typeof 123; // number
如果你通过构造函数创建数字和字符串,比如var foo = new String("foo"),你应该记住typeof可能会返回foo的对象。
也许一个更简单的检查类型的方法是利用underscore.js中的方法(带注释的源代码可以在这里找到),
var toString = Object.prototype.toString;
_.isString = function (obj) {
return toString.call(obj) == '[object String]';
}
这将返回一个布尔值true:
_.isString("Jonathan"); // true
_.isString(new String("Jonathan")); // true
//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。
创建了一个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寄予厚望,但它们的速度慢得可怕。
或者只使用isNaN()的倒数:
if(!isNaN(data))
do something with the number
else
it is a string
是的,使用jQuery的$. isnumeric()更有趣。