有人知道如何在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;

}

其他回答

最好的方法是使用isNaN +类型转换:

更新的all-in方法:

function isNumber(n) { return !isNaN(parseFloat(n)) && !isNaN(n - 0) }

使用regex也一样:

function isNumber(n) { return /^-?[\d.]+(?:e-?\d+)?$/.test(n); } 

------------------------

isNumber('123'); // true  
isNumber('123abc'); // false  
isNumber(5); // true  
isNumber('q345'); // false
isNumber(null); // false
isNumber(undefined); // false
isNumber(false); // false
isNumber('   '); // false

你正在寻找isNaN():

console.log(!isNaN(123)); console.log(!isNaN(-1.23)); console.log(!isNaN(5-2)); console.log(!isNaN(0)); console.log(!isNaN(“0”)); console.log(!isNaN(“2”)); console.log(!isNaN(“Hello”)); console.log(!isNaN(“2005/12/12”));

参见JavaScript isNaN()函数在MDN。

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

效率测试

我知道我该怎么用…

isNaN(parseFloat(n)) && !isNaN(n - 0)} 函数isNumberRE (n){返回/ ^ - ? (\ d。)+ (?:e - ? \ d +) ?美元/ test (n);} function test(fn, timerLabel) { console.time (timerLabel) For (i = 0;I < 1000000;我+ +){ const num = Math.random() * 100 const isNum = fn(num) } console.timeEnd (timerLabel) } test(isNumber, "Normal way") test(isNumberRE, "RegEx方式")

Normal way: 25.103271484375 ms
RegEx way: 334.791015625 ms
function IsNumeric(num) {
    return ((num >=0 || num < 0)&& (parseInt(num)==num) );
}