简体   繁体   English

Javascript-强制输入特定数据类型或仅接受数字输入

[英]Javascript - Force specific data type input OR accept only digits in input

Just starting out on my coding journey. 刚开始我的编码之旅。 I have this prompt and I'm trying to force the user to only input numbers. 我有此提示,我正试图强制用户仅输入数字。 any other characters are not allowed. 不允许使用任何其他字符。 Any idea how I can do this? 知道我该怎么做吗?

var num = prompt("Enter number");

I've tried 我试过了

var num=Number(prompt("Enter number"));

I've also tried making a loop like this but i know prompt returns a string: 我也尝试过像这样的循环,但我知道提示会返回一个字符串:

while (typeof(num)!=='number'{
        alert("You did not enter a number);
        var num=prompt("Enter number"));}

I've also tried: 我也尝试过:

var num= Number(prompt("Enter number"));
while (num===/==NaN){
        alert("You did not enter a number);
        var num=Number(prompt("Enter number"));}
alert("You did enter a number");   

Entering any non number characters into the Number prompt results in NaN, so I thought that if the answer is NaN every time non-numerical characters are entered, then the loop would trigger, and otherwise it wouldn't but that doesn't seem to be the case for some reason. 在“数字”提示中输入任何非数字字符会导致NaN,因此我认为,如果每次输入非数字字符时答案都是NaN,则循环将触发,否则不会触发,但这似乎不会出于某种原因会如此。 Any help would be appreciated :) 任何帮助,将不胜感激 :)

var answer = prompt("Enter a number:");
while (!/^[0-9]+$/.test(answer)) {
    alert("You did not enter a number.");
    answer = prompt("Enter a number: ");
}
alert("You entered a number.");

How does this work? 这是如何运作的?

/^[0-9]+$/ is known as a regular expression. /^[0-9]+$/被称为正则表达式。 ^ specifies start of the string, $ specifies the end of the string, [0-9] specifies a digits, and + specifies one or more occurrences of . ^指定字符串的开头, $指定字符串的结尾, [0-9]指定一个数字,而+指定one or more occurrences of The given regular expression says "starting from the start of the string up to the end of the string, there should be one or more occurrences of a digit, and nothing else." 给定的正则表达式说:“从字符串的开头到字符串的结尾,应该有一个或多个数字出现,而没有别的。” The nothing else part comes in because we are not accepting anything other than digits. 之所以nothing else是因为我们不接受数字以外的任何东西。 If we were, we would put them in the regular expression. 如果是的话,我们会将它们放在正则表达式中。

/^[0-9]+$/.test returns a boolean depending on whether or not the string matches the given regular expression. /^[0-9]+$/.test根据字符串是否匹配给定的正则表达式返回一个布尔值。

Prompts aren't usually the best for inputs since they do not allow any control, but if you're okay with a while loop this might be a good solution: 提示通常不是输入的最佳选择,因为它们不允许任何控制,但是如果您可以使用while循环,那么这可能是一个不错的解决方案:

var answer = prompt("Enter number")
while (answer !== parseInt(answer, 10).toString()) {
    alert("Please enter only numbers!");
    answer = prompt("Enter number");
}

parseInt(answer, 10) "extracts" Numbers from Strings (the second argument is the base, in our case 10 ie decimal). parseInt(answer, 10)从字符串中“提取”数字(第二个参数是基数,在我们的例子中为10即十进制)。 parseInt("5", 10) is 5 , and parseInt("5foo", 10) is also 5 . parseInt("5", 10)5parseInt("5foo", 10)也是5

Basically, if the user enters an integer into the prompt , then parseInt(answer, 10).toString() === answer is true. 基本上,如果用户在prompt输入一个整数,则parseInt(answer, 10).toString() === answer为true。 We use .toString() to convert the resulting Number to String so we can compare it with the actual value that the user entered, which is always stored as a String in case of prompt . 我们使用.toString()所得到的数值至字符串转换,所以我们可以与用户输入的实际值,它总是存储在的情况下一个字符串进行比较prompt

We can use this logic to check if the user actually entered an integer or not. 我们可以使用此逻辑来检查用户是否实际输入了整数。

That said, I would really recommend you to use something like <input type="number"> which would 'enforce' numeric inputs in a much easier/straightforward way. 就是说,我真的建议您使用类似<input type="number">这样的东西,它可以以一种更容易/直接的方式来“强制”数字输入。

So, on top of the regex solution posted, here's a summation of both @namanyayG's, Barmar's and @evolutionxbox's answers: 因此,在发布的正则表达式解决方案之上,这是@ namanyayG,Barmar和@evolutionxbox的答案的总和:

var num = Number(prompt("Enter whole number"));

while (num !== parseInt(num).toString()) {
    alert("Please enter only numbers!");
    num = prompt("Enter number");
}

OR for Float numbers: 或浮点数:

var num = prompt("Enter whole number");

while (num !== parseFloat(num).toString()) {
    alert("Please enter only numbers!");
    num = prompt("Enter number");
}

OR 要么

var num = Number(prompt("Enter whole number"));

while (isNaN(num)!=="false"){
    alert("You did not enter a whole number");
    var num = prompt("Enter number");
}

For some unknown to me reason, isNaN(num)!=="false" is not the same as isNaN(num)==/==="true" 由于某些我不知道的原因, isNaN(num)!=="false"isNaN(num)==/==="true"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM