gpt4 book ai didi

javascript - 如何正确使用indexOf来检查数组中是否有某些内容

转载 作者:行者123 更新时间:2023-11-28 13:21:13 25 4
gpt4 key购买 nike

我想在这个猜谜游戏中检查用户输入的颜色是否在数组列表中。但是当你输入列表中的颜色时,它一直说它不是

var guess_input;
var target;
var colors = ["blue", "cyan", "gold", "gray", "green", "magenta", "orange",
"red", "white", "yellow"
]
var finished = false;
var guesses = 0;
var pos;


function do_game() {
var random_number = Math.floor(Math.random() * (colors.length - 1));
target = colors[random_number];

while (!finished) {
guess_input = prompt("I am thinking of one of these colors: \n\n" + colors.join() +
"\n\n What color am I thinking of?");
guesses++;
finished = check_guess();
}
}

function check_guess() {
if (colors.indexOf(guess_input) > -1) {
alert(
"This is not a color from the list ! Please pick a color from the list\n\n"
);
return false;
}
}

最佳答案

你的条件是倒退的:

function check_guess() {
if (colors.indexOf(guess_input) === -1) { // -1 means not found! you have > -1 which means found!
alert(
"This is not a color from the list ! Please pick a color from the list\n\n"
);
return false;
}
else return true;
}

在某些情况下您还需要返回 true 以避免无限循环。

关于javascript - 如何正确使用indexOf来检查数组中是否有某些内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32912737/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com