提示用户输入,感谢他们输入Javascript

时间:2018-04-24 19:34:07

标签: javascript prompt

第一个提示出现,没有其他任何事情发生,即使我输入一个数字或尝试在没有输入任何内容的情况下完成提示。

到目前为止,我已经编写了这段代码:

var ratingEntry = prompt("We would like for you to review . Please enter a 
rating between 0.0 - 5.0?");

if (ratingEntry === undefined) {
    prompt('Please enter a rating from 0-5!');
} else if (ratingEntry === 0) {
teacherRatings.push('ratingEntry');
    prompt('Thank you!');
} else if (ratingEntry === 1) {
    teacherRatings.push('ratingEntry');
    prompt('Thank you!');
}

我已多次调整它无济于事。

4 个答案:

答案 0 :(得分:0)

prompt将返回string。你需要总是捕获它来进行比较,所以我会这样做:

var message = "We would like for you to review . Please enter a rating between 0.0 - 5.0?";

while(ratingEntry = prompt(message)) {
    if (ratingEntry === '' || ratingEntry < 0 || ratingEntry > 5) {
        message = 'Please enter a rating from 0-5!');
    } else {
        break;
    }
}

等。因为您使用===来比较值和类型(例如1 === 11 !== '1',但是1 == '1'

答案 1 :(得分:0)

要比较整数,你需要首先将ratingEntry解析为Integer然后进行比较,对于第一个条件它是空白而不是未定义,所以在第一个条件下检查OR

var ratingEntry = prompt("We would like for you to review . Please enter a rating between 0.0 - 5.0?");
if (typeof ratingEntry === undefined || ratingEntry.trim() == '') {
    prompt('Please enter a rating from 0-5!');
} else if (parseInt(ratingEntry) === 0) {
    teacherRatings.push('ratingEntry');
    prompt('Thank you!');
} else if (parseInt(ratingEntry) === 1) {
    teacherRatings.push('ratingEntry');
    prompt('Thank you!');
}

最后一件事我不确定你在使用这段代码做什么,但它应该是这样的 使用 teacherRatings.push(ratingEntry);

而不是

teacherRatings.push('ratingEntry');  //this push ratingEntry as string in teacherRatings not as a value of variable

答案 2 :(得分:0)

你遇到的问题是提示返回一个字符串,你确实检查了没有类型coersion的相等性。

1 === 1 is true "1" === 1 is false

基本上"1"是一个字符串,1是一个整数。

===更改为==,您会忽略&#34;输入&#34;校验。或者只检查"1"而不是1

答案 3 :(得分:0)

您可能想要将输入解析为Float,然后使用while循环直到输入有效:

var ratingEntry = prompt("We would like for you to review . Please enter a rating between 0.0 - 5.0?");
var ratingNum = parseFloat(ratingEntry)

while (isNaN(ratingNum) || ratingNum < 0 || ratingNum > 5) {
  ratingNum = parseFloat(prompt('Please enter a rating from 0-5!'));
}
teacherRatings.push(ratingNum);
prompt('Thank you!');