var num = "987238";
if(num.match(/^-?\d+$/)){//valid integer (positive or negative)}else if(num.match(/^\d+\.\d+$/)){//valid float}else{//not valid number}
function isNumeric(str) {if (typeof str != "string") return false // we only process strings!return !isNaN(str) && // use type coercion to parse the _entirety_ of the string (`parseFloat` alone does not do this)...!isNaN(parseFloat(str)) // ...and ensure strings of whitespace fail}
要检查变量(包括字符串)是否为数字,请检查它是否不是数字:
无论变量内容是字符串还是数字,这都有效。
isNaN(num) // returns true if the variable does NOT contain a valid number
示例
isNaN(123) // falseisNaN('123') // falseisNaN('1e10000') // false (This translates to Infinity, which is a number)isNaN('foo') // trueisNaN('10px') // trueisNaN('') // falseisNaN(' ') // falseisNaN(false) // false
当然,如果需要,你可以否定它。例如,要实现你给出的IsNumeric示例:
function isNumeric(num){return !isNaN(num)}
要将包含数字的字符串转换为数字:
只有当字符串只有包含数字字符时才有效,否则它返回NaN。
+num // returns the numeric value of the string, or NaN// if the string isn't purely numeric characters
parseInt(num) // extracts a numeric value from the// start of the string, or NaN.
示例
parseInt('12') // 12parseInt('aaa') // NaNparseInt('12px') // 12parseInt('foo2') // NaN These last three mayparseInt('12a5') // 12 be different from whatparseInt('0x10') // 16 you expected to see.
function isNonScientificNumberString(o) {if (!o || typeof o !== 'string') {// Should not be given anything but strings.return false;}return o.length <= 15 && o.indexOf('e+') < 0 && o.indexOf('E+') < 0 && !isNaN(o) && isFinite(o);}
function isStringNumeric(str_input){//concat a temporary 1 during the modulus to keep a beginning hex switch combination from messing us up//very simple and as long as special characters (non a-z A-Z 0-9) are trapped it is finereturn '1'.concat(str_input) % 1 === 0;}
function isNumber(str) {if (typeof str != "string") return false // we only process strings!// could also coerce to string: str = ""+strreturn !isNaN(str) && !isNaN(parseFloat(str))}
isNotNumber(value: string | number): value is string {return Number.isNaN(Number(this.smartImageWidth));}isNumber(value: string | number): value is number {return Number.isNaN(Number(this.smartImageWidth)) === false;}
var width: number|string;width = "100vw";
if (isNotNumber(width)){// the compiler knows that width here must be a stringif (width.endsWith('vw')){// we have a 'width' such as 100vw}}else{// the compiler is smart and knows width here must be numbervar doubleWidth = width * 2;}
/*** Returns true if 'candidate' is a finite number or a string referring (not just 'including') a finite number* To keep in mind:* Number(true) = 1* Number('') = 0* Number(" 10 ") = 10* !isNaN(true) = true* parseFloat('10 a') = 10** @param {?} candidate* @return {boolean}*/function isReferringFiniteNumber(candidate) {if (typeof (candidate) === 'number') return Number.isFinite(candidate);if (typeof (candidate) === 'string') {return (candidate.trim() !== '') && Number.isFinite(Number(candidate));}return false;}
并以这种方式使用它:
if (isReferringFiniteNumber(theirValue)) {myCheckedValue = Number(theirValue);} else {console.warn('The provided value doesn\'t refer to a finite number');}
/*** My necessity was met by the following code.*/
if (input === null) {// Null input} else if (input.trim() === '') {// Empty or whitespace-only string} else if (isFinite(input)) {// Input is a number} else {// Not a number}
而且,这是我生成表的JavaScript:
/*** Note: JavaScript does not print numeric separator inside a number.* In that single case, the markdown output was manually corrected.* Also, the comments were manually added later, of course.*/
let inputs = [123, '123', 12.3, '12.3', ' 12.3 ',1_000_000, '1_000_000','0b11111111', '0o377', '0xFF','', ' ','abc', '12.34Ab!@#$','10e100', '10e1000',null, undefined, Infinity];
let markdownOutput = `| \`input\` | \`!isNaN(input)\` or <br>\`+input === +input\` | \`!isNaN(parseFloat(input))\` | \`isFinite(input)\` | Comment || :---: | :---: | :---: | :---: | :--- |\n`;
for (let input of inputs) {let outputs = [];outputs.push(!isNaN(input));outputs.push(!isNaN(parseFloat(input)));outputs.push(isFinite(input));
if (typeof input === 'string') {// Output with quotationsconsole.log(`'${input}'`);markdownOutput += `| '${input}'`;} else {// Output without quotesconsole.log(input);markdownOutput += `| ${input}`;}
for (let output of outputs) {console.log('\t' + output);if (output === true) {markdownOutput += ` | <div style="color:limegreen">true</div>`;// markdownOutput += ` | ✔️`; // for stackoverflow} else {markdownOutput += ` | <div style="color:orangered">false</div>`;// markdownOutput += ` | ❌`; // for stackoverflow}}
markdownOutput += ` ||\n`;}
// Replace two or more whitespaces with $nbsp;markdownOutput = markdownOutput.replaceAll(` `, ` `);
// Print markdown to consoleconsole.log(markdownOutput);