检查一个字符串是否只包含整数数字的主要问题是没有关于如何执行此操作的定义标准。 这可能导致不同的实现返回不同的结果,这可能难以理解和调试。
I want to check if a string only contains integer digits numbers. For example: <code>var str = "123"; // return true; var str = "123a"; // return false; </code> A: You can use <code>/^d+$/.test(str)</code>. This will test whether the string consists of one or more digits. If you want to allow for a leading minus sign, then use <code>/^-?d+$/.test(str)</code>. If you want to allow for an optional decimal point and fractional part, then use <code>/^-?d+(.d+)?$/.test(str)</code>. If you want to allow for an optional exponent, then use <code>/^-?(d+(.d*)?|.d+)([eE][-+]?d+)?$/.test(str)</code>. The last two expressions are the ones used by the built-in function <code>isFinite()</code>, which is what you should be using if your goal is to test whether a string can be converted into a number. (If your goal is something else, please edit your question.)
条件语句
条件语句是 JavaScript 中的一个强大工具。 它们允许您根据满足的特定条件来控制代码流。
条件语句的一个常见用途是检查变量是否等于某个值。 例如,您可能希望在用户输入无效时显示一条错误消息。
您可以使用 if 语句来测试条件是真还是假。 以下代码示例检查用户的输入是否介于 1 和 10 之间:
if (userInput <= 10) { // 显示错误信息 } else { // 显示正常响应 } 您也可以使用 switch 语句一次测试多个条件。 下面的代码示例检查用户的输入是否在 1 到 10 之间,长度至少为 3 个字符,并且以字母开头: switch (userInput) { case "1": case "2": case "3":案例“a”:案例“b”:案例“c”:中断; 默认值:// 显示错误消息 }
如果别的
If 是 JavaScript 中的条件运算符。 它允许您在两种可能的结果之间进行选择。 第一个结果是条件,第二个结果是 if 语句的结果。
如果你想检查一个数字是偶数还是奇数,你可以使用下面的代码:
if (number % 2 == 0) { //偶数 } else { //奇数 }
如果数字不是偶数,则执行 else 子句。