有人知道如何在JavaScript中检查变量是数字还是字符串吗?


当前回答

Typeof在大多数情况下都很适合我。您可以尝试使用if语句

if(typeof x === 'string' || typeof x === 'number') {
    console.log("Your statement");
}

x是任意变量名

其他回答

@BitOfUniverse的答案很好,我想出了一个新方法:

function isNum(n) {
    return !isNaN(n/0);
}

isNum('')  // false
isNum(2)   // true
isNum('2k') // false
isNum('2')  //true

我知道0不可能是被除数,但这里函数是完美的。

jQuery使用这个:

function isNumber(obj) {
  return !isNaN( parseFloat( obj ) ) && isFinite( obj );
}

呃,不如这样:

function IsString(obj) {
    return obj !== undefined && obj != null && obj.toLowerCase !== undefined;
}

经过几个月后的进一步检查,这只能保证obj是一个定义了方法或属性名称toLowerCase的对象。我为我的回答感到惭愧。请参阅投票最多的类型。

我认为将var转换为字符串会降低性能,至少在最新的浏览器中进行的测试显示了这一点。

如果你关心性能,我会用这个:

typeof str === "string" || str instanceof String

用于检查变量是否为字符串(即使您使用var str = new string ("foo"), str instanceof string将返回true)。

至于检查它是否是一个数字,我会选择本地:isNaN;函数。

我发现的最好的方法是检查字符串上的方法,即:

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));

将提醒“对象”。