Pure JavaScript: Function to Check if a Value is Numeric
In jQuery, the isNumeric() function verifies whether a value represents an integer. While JavaScript does not have a similar built-in function, you can implement your own custom check.
To create a function that mimics isNumeric() in pure JavaScript, follow these steps:
Define the isNumeric() Function:
<code class="javascript">function isNumeric(n) {</code>
Check if the Value is a Number:
Use !isNaN(parseFloat(n)) to determine if the value can be successfully parsed as a floating-point number.
Ensure the Value is Finite:
Add && isFinite(n) to verify that the number is finite, excluding Infinity and NaN.
Complete the Function Definition:
<code class="javascript"> return !isNaN(parseFloat(n)) && isFinite(n); }</code>
Example Usage:
<code class="javascript">const value = 123; const isNumber = isNumeric(value); // Returns true</code>
Note:
It's important to avoid using parseInt() to check for numeric values. While it may initially appear to work, it can lead to unexpected results and is not a reliable way to determine numeric values in JavaScript.
The above is the detailed content of How to Implement a Custom Numeric Check Function in Pure JavaScript?. For more information, please follow other related articles on the PHP Chinese website!