有人知道如何在JavaScript中检查变量是数字还是字符串吗?
当前回答
类型检查
你可以使用typeof操作符检查变量的类型:
typeof variable
值检查
下面的代码对数字返回true,对其他任何值返回false:
!isNaN(+variable);
其他回答
呃,不如这样:
function IsString(obj) {
return obj !== undefined && obj != null && obj.toLowerCase !== undefined;
}
经过几个月后的进一步检查,这只能保证obj是一个定义了方法或属性名称toLowerCase的对象。我为我的回答感到惭愧。请参阅投票最多的类型。
或者只使用isNaN()的倒数:
if(!isNaN(data))
do something with the number
else
it is a string
是的,使用jQuery的$. isnumeric()更有趣。
Typeof在大多数情况下都很适合我。您可以尝试使用if语句
if(typeof x === 'string' || typeof x === 'number') {
console.log("Your statement");
}
x是任意变量名
仅供参考,如果你使用jQuery你有
$.isNumeric()
来处理这个问题。更多详情请访问http://api.jquery.com/jQuery.isNumeric/
你正在寻找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。