3 ways to judge: 1. Use the isFinite() function, the syntax is "isFinite (string)", return true to indicate that it is a number, and return false to indicate that it is not a number. 2. Use the isNaN() function, the syntax is "isNaN (string)", return true to indicate that it is not a number, and return false to indicate that it is a number. 3. Use the test() function and regular expressions, the syntax is "/^[0-9] .?[0-9]*/.test(string)", and return true to represent a number.
The operating environment of this tutorial: Windows 7 system, ECMAScript version 6, Dell G3 computer.
es6 3 ways to determine whether a string is a number
Method 1: Use the isFinite() function
isFinite() function is used to check whether its parameter is infinity, which can also be understood as whether it is a finite number.
isFinite(value)
That is, whether the parameter value passed in is a finite number.
Returning true means it is a number, returning false means it is not a number
console.log(isFinite("123")); // true console.log(isFinite("beline")); //false console.log(isFinite(NaN)); // false console.log(isFinite(undefined)); // false
##Method 2: Use the isNaN() function
isNaN() function is used to check whether its argument is a non-numeric value.isNaN(value)
console.log(isNaN(1)); // false console.log(isNaN("12.3")); // false console.log(isNaN("beline")); //true console.log(isNaN(NaN)); // true console.log(isNaN(undefined)); // true
Method 3: Using the test() function and regular expressions
The test() method is used to detect whether a string matches a certain pattern.If the string Returns true if there is a matching value, otherwise returns false.Regular expression:As long as If it is a number (including positive and negative integers, 0 and positive and negative floating point numbers), it returns true, otherwise it returns false./^[0-9] .?[0-9]*/
, determine whether it is a number
var patt=/^[0-9]+.?[0-9]*/; console.log(patt.test(12)); // true console.log(patt.test("12.3")); // true console.log(patt.test("beline")); //false console.log(patt.test(NaN)); // false console.log(patt.test(undefined)); // false
Getting started with web front-end)
The above is the detailed content of How to determine whether a string is a number in es6. For more information, please follow other related articles on the PHP Chinese website!