gpt4 book ai didi

javascript - 如何检查数组中是否存在字符串?

转载 作者:太空宇宙 更新时间:2023-11-04 15:39:40 25 4
gpt4 key购买 nike

var colors = ["blue", "cyan", "gold", "grey", "orange", "red"];
var gussess = 0;
var color_choosed;
var color_guessed;

function game() {
color_choosed = "grey";
color_guessed = prompt("I'm thinking of one of these colors");
if (colors.indexOf(color_guessed) > colors.indexOf(color_choosed))
alert("The color choosed is after my color");
else if (colors.indexOf(color_guessed) < colors.indexOf(color_choosed))
alert("The coloris befor my color");
else if (colors.indexOf(color_guessed) == colors.indexOf(color_choosed))
alert("congrats you are right my color is " + color_guessed);
else if (color_guessed not in colors)
alert("The color is not in the list");
}

我想编写一个 if 语句来检查用户是否放置了不在列表中的颜色..做些什么?提醒他该颜色不在列表中

最佳答案

I want to write an if statement to check if the user has put a color not in the list ..

这是if语句,您可以使用它来检查用户的输入是否在您的数组中:

if(colors.indexOf(color_guessed) === -1) { // code here }

重要通知: indexOf() 如果数组中不存在该值,则返回-1。这会给您的代码带来一些额外的副作用。为了解决这个问题,您应该将最后一个 if 语句移到开头,使其成为第一个语句,如下所示:

function game() {
color_choosed = "grey";
color_guessed = prompt("I'm thinking of one of these colors");
if(colors.indexOf(color_guessed) === -1) // color not found in array
alert("The color is not in the list");
else if (colors.indexOf(color_guessed) > colors.indexOf(color_choosed)) // color is after
alert("The color choosed is after my color");
else if (colors.indexOf(color_guessed) < colors.indexOf(color_choosed)) // color is before
alert("The coloris befor my color");
else if (color_guessed === color_choosed) // colors match!
alert("congrats you are right my color is " + color_guessed);
}

关于javascript - 如何检查数组中是否存在字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44000352/

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