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;
// Begin public utility /getVarType/
// Returns 'Function', 'Object', 'Array',
// 'String', 'Number', 'Boolean', or 'Undefined'
getVarType = function ( data ){
if (undefined === data ){ return 'Undefined'; }
if (data === null ){ return 'Null'; }
return {}.toString.call(data).slice(8, -1);
};
// End public utility /getVarType/
正确性的例子
var str = new String();
console.warn( getVarType(str) ); // Reports "String"
console.warn( typeof str ); // Reports "object"
var num = new Number();
console.warn( getVarType(num) ); // Reports "Number"
console.warn( typeof num ); // Reports "object"
var list = [];
console.warn( getVarType( list ) ); // Reports "Array"
console.warn( typeof list ); // Reports "object"
因为字符串'1234'和typeof将显示'string',而相反的情况永远不会发生(typeof 123将永远是数字),最好是使用一个简单的正则表达式/^\-?\d+$/.test(var)。或者更高级的匹配浮点数、整数和负数的/^[\-\+]?[\d]+\.?(\d+)?$/.test的重要方面是,如果var不是字符串,它不会抛出异常,它的值可以是任何东西。< / p >
var val, regex = /^[\-\+]?[\d]+\.?(\d+)?$/;
regex.test(val) // false
val = '1234';
regex.test(val) // true
val = '-213';
regex.test(val) // true
val = '-213.2312';
regex.test(val) // true
val = '+213.2312';
regex.test(val) // true
val = 123;
regex.test(val) // true
val = new Number(123);
regex.test(val) // true
val = new String('123');
regex.test(val) // true
val = '1234e';
regex.test(val) // false
val = {};
regex.test(val) // false
val = false;
regex.test(val) // false
regex.test(undefined) // false
regex.test(null) // false
regex.test(window) // false
regex.test(document) // false