有人知道如何在JavaScript中检查变量是数字还是字符串吗?
当前回答
仅供参考,如果你使用jQuery你有
$.isNumeric()
来处理这个问题。更多详情请访问http://api.jquery.com/jQuery.isNumeric/
其他回答
仅供参考,如果你使用jQuery你有
$.isNumeric()
来处理这个问题。更多详情请访问http://api.jquery.com/jQuery.isNumeric/
Typeof在大多数情况下都很适合我。您可以尝试使用if语句
if(typeof x === 'string' || typeof x === 'number') {
console.log("Your statement");
}
x是任意变量名
对于数字检测,以下文章来自Douglas Crockford的JavaScript: the Good Parts:
isFinite函数是确定一个值是否可以用作数字的最佳方法,因为它拒绝NaN和Infinity。不幸的是,isFinite将尝试将其操作数转换为一个数字,因此如果一个值实际上不是一个数字,那么它不是一个好的测试。你可能想要定义自己的isNumber函数:
var isNumber = function isNumber(value) { return typeof value === 'number' &&
isFinite(value);
};
@BitOfUniverse的答案很好,我想出了一个新方法:
function isNum(n) {
return !isNaN(n/0);
}
isNum('') // false
isNum(2) // true
isNum('2k') // false
isNum('2') //true
我知道0不可能是被除数,但这里函数是完美的。
我发现的最好的方法是检查字符串上的方法,即:
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));
将提醒“对象”。