有人知道如何在JavaScript中检查变量是数字还是字符串吗?
当前回答
function IsNumeric(num) {
return ((num >=0 || num < 0)&& (parseInt(num)==num) );
}
其他回答
如果你处理的是文字符号,而不是构造函数,你可以使用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
试试这个,
<script>
var regInteger = /^-?\d+$/;
function isInteger( str ) {
return regInteger.test( str );
}
if(isInteger("1a11")) {
console.log( 'Integer' );
} else {
console.log( 'Non Integer' );
}
</script>
//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。
因为像'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单独就可以了。
Typeof在大多数情况下都很适合我。您可以尝试使用if语句
if(typeof x === 'string' || typeof x === 'number') {
console.log("Your statement");
}
x是任意变量名