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


当前回答

//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。

其他回答

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

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

将提醒“对象”。

能把它除以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)\]/);

你觉得这个怎么样?

const numberOrString='10' 
const isNumber = !isNaN(numberOrString*1) 

呃,不如这样:

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

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