我试图将数组的每个元素与用户输入进行比较,以便在用户的输入与数组的任何元素不匹配时生成一条消息。我用来做的代码如下。
var guess_input;
var finished = false;
var colors = ["Aqua", "BurlyWood", "Cornsilk", "DarkGrey", "DarkRed", "Indigo", "LightGrey"];
while (!finished) {
guess_input = prompt("I'm thinking of one of these colors:\n\n" + "Aqua, BurlyWood, Cornsilk, DarkGrey, DarkRed, Indigo, LightGrey" + "\n\nWhat is the color I'm thinking of?");
finished = check_guess();
}
}
function check_guess() {
if (guess_input != colors[0] || guess_input != colors[1] || guess_input != colors[2] || guess_input != colors[3]) {
alert("Sorry, I don't recognize that color!\n\n" + "Please try again.");
return false;
}
}
这段代码的问题是,如果我只从数组中选择一个元素,它工作得很好。但是当我使用“OR”运算符时,它不起作用。有没有更好的方法来做到这一点?我是 java 脚本新手。
谢谢!
最佳答案
您可以使用logical AND运算符 &&
,因为您需要检查所有要检查的颜色。
if (guess_input != colors[0] && guess_input != colors[1] && guess_input != colors[2] && guess_input != colors[3]) {
alert("Sorry, I don't recognize that color!\n\n" + "Please try again.");
return false;
}
对于工作代码,您还需要为找到的颜色返回 true
。
var guess_input;
var finished = false;
var colors = ["Aqua", "BurlyWood", "Cornsilk", "DarkGrey", "DarkRed", "Indigo", "LightGrey"];
while (!finished) {
guess_input = prompt("I'm thinking of one of these colors:\n\n" + "Aqua, BurlyWood, Cornsilk, DarkGrey, DarkRed, Indigo, LightGrey" + "\n\nWhat is the color I'm thinking of?");
finished = check_guess();
}
function check_guess() {
if (guess_input != colors[0] && guess_input != colors[1] && guess_input != colors[2] && guess_input != colors[3]) {
alert("Sorry, I don't recognize that color!\n\n" + "Please try again.");
return false;
}
return true; // necessary, otherwise the function returns undefined, which is a falsy value
}
关于javascript - 将变量与数组元素进行比较 (javascript),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39320668/