如何确保用户输入是js中的有效字符串

时间:2017-02-28 16:36:24

标签: javascript arrays

我是JS的新手, 如何确保用户输入是有效的字符串? 如果字符串在数组内部,则游戏应该继续。 如果字符串在数组之外,游戏应该要求用户再次输入他们的猜测。

var color = ["AliceBlue","Black","FireBrick","GreenYellow","LightBlue","Ivory","MediumBlue","Indigo","SpringGreen","Moccasin"];

var target;
var guess_input_text;
var guess_input;
var finished = false;
var guesses = 0;
var rightAnswer;
var i = 0;

function do_game() {
    var random_number = Math.random()* color.length;
    var random_number_interger = Math.floor(random_number);
    target = random_number_interger + 1;
    rightAnswer = color[target];


    while(!finished) {
        guess_input_text = prompt("I am thinking of one of these colors:\n\n" + color.sort()+ "\n\n The right answer is\n" + rightAnswer);
        guess_input = guess_input_text;
        guesses +=1;
       finished = check_guess();

    }
}


function check_guess() {



     if(guess_input < rightAnswer){

          console.log("Hint: your color is alphabetically lower than mine")
          return false;
      }
      else if( guess_input > rightAnswer) {

         console.log("Hint: your color is alphabetically higher than mine ")
          return false;
      }
     else (guess_input == rightAnswer)
      {
          console.log("Congrats!!!")
          return true;

      }  

    )
}

2 个答案:

答案 0 :(得分:1)

您可以使用indexOf检查颜色数组中guess_input的位置。如果它不存在,它将返回-1。

所以:

function check_guess() {
    if (color.indexOf(guess_input) < 0) {
        console.log("Not a valid colour, try again.");
        return false;
    }
    return true;
}

答案 1 :(得分:0)

您可以将Array.prototype.find函数与ES6箭头函数一起使用,使其更加快捷。

if(color.findIndex(e => e === guess_input) === -1){
    alert("Please guess again!);
}

以上代码提醒用户再次猜测是否在阵列中找不到guess_input