Невозможно проверить приглашение на наличие пустой строки - PullRequest
0 голосов
/ 15 января 2020

Вот мой код:

    let guessTheNumber = () => {
        let randomNumber = Math.round((Math.random()) * 10); //generating a random number from 1 to 10
        console.log(randomNumber); //added this just to see what number was generated
        let question = +prompt('Please, try to guess the number from 1 to 10!'); // by using unary plus I want prompt to return a number, NOT a string
        if (question === randomNumber) {
            alert('Wow, you are quite lucky. Nice job!'); //this one works 
        }
        else if (question !== randomNumber) {
            alert('Nope'); //this one is also easy to check
        }
        else if (question === "") {
            alert('You did not enter anything!'); 
        }
        else {
            alert('Why did you cancel?');
        }
    }
    guessTheNumber();

Я могу успешно проверить question, когда он равен randomNumber переменной или нет. Но когда я пытаюсь что-то предупредить, если есть пустая строка (нажав «ОК» без ввода) или ноль (нажав «Отмена»), программа завершается неудачей.

Ответы [ 2 ]

1 голос
/ 15 января 2020

(+) перед prompt будет преобразовывать ответ в число , поэтому, если пользователь отменил или оставил приглашение пустым, он всегда вернет 0

Так что если вы нужно проверить на cancel, вам нужно удалить (+), тогда prompt вернет string или null, поэтому вам понадобятся дополнительные логи c.

let guessTheNumber = () => {
  // using 'Math.ceil' as @symlink mentioned
  let randomNumber = Math.ceil((Math.random()) * 10);
  console.log(randomNumber);
  let question = prompt('Please, try to guess the number from 1 to 10!');

  // check for cancel 'null'
  if (question == null) {
    alert('Why did you cancel?');
    // you need to exit so it won't prompt again
    return
  }
  // parseInt() function parses a string argument and returns an integer
  else if (parseInt(question, 10) === randomNumber) {
    alert('Wow, you are quite lucky. Nice job!');
  }
  // empty value
  else if (question === '') {
    alert('You did not enter anything!');
    // run again
    guessTheNumber();
  }
  // not a number
  else if (isNaN(question)) {
    alert('Please enter a number');
    // run again
    guessTheNumber();
  }
  // wrong answer
  else {
    alert('Nope!')
    // run again
    guessTheNumber();
  }
}
guessTheNumber();
0 голосов
/ 15 января 2020

Во-первых, вы хотите Match.ceil() ваше случайное число, а не Math.round(). Затем для неверных данных проверьте, является ли предположение нулевым, а не числом или пустой строкой с:

!guess || isNaN(guess) || guess.trim() === ""

let guessTheNumber = () => {
    let ranNum = Math.ceil((Math.random()) * 10)
    
    let guess = prompt("Please, try to guess the number from 1 to 10!")
    
    if (parseInt(guess, 10) === ranNum) {
        alert("Wow, you are quite lucky. Nice job!")
    }else if(!guess || isNaN(guess) || guess.trim() === ""){
        alert("You didn't enter a number")
    }else{
        alert("Nope")
    }    
    console.log(guess, ranNum)
}
guessTheNumber();
...