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


当前回答

我发现的同时考虑正数和负数的最好方法是: O'Reilly Javascript和DHTML烹饪书:

function isNumber(elem) {
var str = elem.value;
var oneDecimal = false;
var oneChar = 0;
// make sure value hasn't cast to a number data type
str = str.toString( );
for (var i = 0; i < str.length; i++) {
    oneChar = str.charAt(i).charCodeAt(0);
    // OK for minus sign as first character
    if (oneChar =  = 45) {
        if (i =  = 0) {
            continue;
        } else {
            alert("Only the first character may be a minus sign.");
            return false;
        }
    }
    // OK for one decimal point
    if (oneChar =  = 46) {
        if (!oneDecimal) {
            oneDecimal = true;
            continue;
        } else {
            alert("Only one decimal is allowed in a number.");
            return false;
        }
    }
    // characters outside of 0 through 9 not OK
    if (oneChar < 48 || oneChar > 57) {
        alert("Enter only numbers into the field.");
        return false;
    }
}
return true;

}

其他回答

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

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

x是任意变量名

检查值是否为string字面值或string对象:

function isString(o) {
    return typeof o == "string" || (typeof o == "object" && o.constructor === String);
}

单元测试:

function assertTrue(value, message) {
    if (!value) {
        alert("Assertion error: " + message);
    }
}

function assertFalse(value, message)
{
    assertTrue(!value, message);
}

assertTrue(isString("string literal"), "number literal");
assertTrue(isString(new String("String object")), "String object");
assertFalse(isString(1), "number literal");
assertFalse(isString(true), "boolean literal");
assertFalse(isString({}), "object");

检查一个数字类似:

function isNumber(o) {
    return typeof o == "number" || (typeof o == "object" && o.constructor === Number);
}
//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。

简单地使用

myVar.constructor == String

or

myVar.constructor == Number

如果要处理定义为对象或字面量并保存的字符串,则不需要使用helper函数。

jQuery使用这个:

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