Ad

Function: If With Interrupting, Return

- 1 answer

I am not able to get values from my prompt function

I need the function to work properly if users input is equal to one of 6 variables, and in "if" condition to stop if input didn't match any. I manipulated with &&, || !, ==, === a lot, nothing works, console.log gives me the same result I'm typing (but with upper cased first letter, lol)

//variables
let r = "Rock";
let p = "Paper";
let s = "Scissor";
let rl = "rock";
let pl = "paper";
let sl = "scissor";
const weapon = [r, p, s];
let playerChoiceUnchecked = prompt("Rock, Paper, or Scissor?");
//functions
function playerChoice(checkPlayer) {
 if (playerChoiceUnchecked == ((!r && !rl) && (!p && !pl) && (!s && !sl))) {
    alert("There's no such weapon");
    return false;
 } else {
    let checkPlayer = playerChoiceUnchecked.charAt(0).toUpperCase() + playerChoiceUnchecked.slice(1);
    //return checkPlayer;
    console.log(checkPlayer); //debug for playerChoice, second part DONE
 }
}
Ad

Answer

Your code could be simplified:

const weapons = ["rock", "paper", "scissor"]

function playerChoice() {
  let playerChoiceUnchecked = prompt("Rock, Paper, or Scissor?");
  if ( !weapons.includes( playerChoiceUnchecked.toLowerCase() ) ) {
    alert("There's no such weapon");
  } else {
    let checkPlayer = playerChoiceUnchecked.charAt(0).toUpperCase() + playerChoiceUnchecked.slice(1);
    console.log(checkPlayer);
  }
}

playerChoice()

Ad
source: stackoverflow.com
Ad