有人知道如何在JavaScript中检查变量是数字还是字符串吗?
当前回答
jQuery使用这个:
function isNumber(obj) {
return !isNaN( parseFloat( obj ) ) && isFinite( obj );
}
其他回答
呃,不如这样:
function IsString(obj) {
return obj !== undefined && obj != null && obj.toLowerCase !== undefined;
}
经过几个月后的进一步检查,这只能保证obj是一个定义了方法或属性名称toLowerCase的对象。我为我的回答感到惭愧。请参阅投票最多的类型。
注意那种类型的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。
你觉得这个怎么样?
const numberOrString='10'
const isNumber = !isNaN(numberOrString*1)
聚会很晚才来;然而,当我想一次性检查某些输入是字符串还是数字时,下面的方法总是很有效。
return !!Object.prototype.toString.call(input).match(/\[object (String|Number)\]/);