Home > Article > Web Front-end > isNaN function in JavaScript: Check if non-numeric value
isNaN function in JavaScript: Check whether it is a non-numeric value, you need a specific code example
In JavaScript, there is a very commonly used function isNaN, used to check Whether a value is not a number. This is a very handy tool for developers to use to determine if an input is numeric, as well as handle numeric and non-numeric logic.
The isNaN function accepts a parameter. If the parameter is a non-numeric value, the function will return true; if the parameter is a number, it will return false. Below are some specific code examples to help us better understand the use of isNaN function.
let userInput = prompt("请输入一个数字:"); if (isNaN(userInput)) { console.log("输入的并不是一个数字!"); } else { console.log("输入的是一个数字。"); }
In this example, we use the prompt function to let the user enter a number. Then check whether the value entered by the user is a non-number through the isNaN function. If it returns true, print "The input is not a number!"; if it returns false, print "The input is a number."
let num1 = 10; let num2 = "20"; let result = num1 + num2; if (isNaN(result)) { console.log("结果是非数字值!"); } else { console.log("结果是:" + result); }
In this example, we define a variable num1 and assign it the value 10. Another variable num2 is assigned the string "20". Then add these two variables and assign them to the result variable. Next, we use the isNaN function to check whether the value of result is not a number. If it returns true, print "The result is a non-numeric value!"; if it returns false, print "The result is:" plus the value of result.
let userInput = prompt("请输入一个数字:"); let num = parseInt(userInput); if (isNaN(num)) { console.log("输入的并不是一个有效的数字!"); } else { console.log("输入的数字是:" + num); }
In this example, we convert the string entered by the user into an integer through the parseInt function. Then use the isNaN function to check if the converted value is not a number. If true is returned, print "The entered number is not a valid number!"; if false is returned, print "The entered number is:" plus the converted value of num.
Summary
In general, the isNaN function is a very practical function in JavaScript, used to check whether a value is a non-number. It is useful when dealing with user input, logic that handles numbers and non-numbers. In development, reasonable use of the isNaN function can effectively handle various numeric and non-numeric situations, improving the stability and readability of the code. The above are some specific code examples, I hope they can help you better understand the use of isNaN function.
The above is the detailed content of isNaN function in JavaScript: Check if non-numeric value. For more information, please follow other related articles on the PHP Chinese website!