有人知道如何在JavaScript中检查变量是数字还是字符串吗?
当前回答
如果你处理的是文字符号,而不是构造函数,你可以使用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。
最好的方法是使用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
你正在寻找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。
能把它除以1吗?
我假设问题将是一个字符串输入,如:"123ABG"
var Check = "123ABG"
if(Check == Check / 1)
{
alert("This IS a number \n")
}
else
{
alert("This is NOT a number \n")
}
我最近就是这么做的。
聚会很晚才来;然而,当我想一次性检查某些输入是字符串还是数字时,下面的方法总是很有效。
return !!Object.prototype.toString.call(input).match(/\[object (String|Number)\]/);