在这里,我从这个页面收集了“好的”,并将它们放入一个简单的测试模式中,供您自行评估。
对于新手来说,console.log是一个内置函数(在所有现代浏览器中都可用),它允许您将结果输出到JavaScript控制台(仔细查看,您会发现),而不必输出到HTML页面。
var isNumeric = function(val){
// --------------------------
// Recommended
// --------------------------
// jQuery - works rather well
// See CMS's unit test also: http://dl.getdropbox.com/u/35146/js/tests/isNumber.html
return !isNaN(parseFloat(val)) && isFinite(val);
// Aquatic - good and fast, fails the "0x89f" test, but that test is questionable.
//return parseFloat(val)==val;
// --------------------------
// Other quirky options
// --------------------------
// Fails on "", null, newline, tab negative.
//return !isNaN(val);
// user532188 - fails on "0x89f"
//var n2 = val;
//val = parseFloat(val);
//return (val!='NaN' && n2==val);
// Rafael - fails on negative + decimal numbers, may be good for isInt()?
// return ( val % 1 == 0 ) ? true : false;
// pottedmeat - good, but fails on stringy numbers, which may be a good thing for some folks?
//return /^-?(0|[1-9]\d*|(?=\.))(\.\d+)?$/.test(val);
// Haren - passes all
// borrowed from http://www.codetoad.com/javascript/isnumeric.asp
//var RE = /^-{0,1}\d*\.{0,1}\d+$/;
//return RE.test(val);
// YUI - good for strict adherance to number type. Doesn't let stringy numbers through.
//return typeof val === 'number' && isFinite(val);
// user189277 - fails on "" and "\n"
//return ( val >=0 || val < 0);
}
var tests = [0, 1, "0", 0x0, 0x000, "0000", "0x89f", 8e5, 0x23, -0, 0.0, "1.0", 1.0, -1.5, 0.42, '075', "01", '-01', "0.", ".0", "a", "a2", true, false, "#000", '1.2.3', '#abcdef', '', "", "\n", "\t", '-', null, undefined];
for (var i=0; i<tests.length; i++){
console.log( "test " + i + ": " + tests[i] + " \t " + isNumeric(tests[i]) );
}