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


当前回答

我认为将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));

将提醒“对象”。

仅供参考,如果你使用jQuery你有

$.isNumeric() 

来处理这个问题。更多详情请访问http://api.jquery.com/jQuery.isNumeric/

注意那种类型的NaN是…“数量”

typeof NaN === 'number'; // 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。

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

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

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

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