功能:如果有中断,return

function: if with interrupting, return

我无法从我的 prompt 函数中获取值

我需要函数在用户输入等于 6 个变量之一时正常工作,并且在 "if" 条件下如果输入不匹配则停止。我用 &&, || !, ==, === 进行了很多操作,但没有任何效果,console.log 给我的结果与我输入的结果相同(但首字母大写,哈哈)

//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
 }
}

您的代码可以简化:

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()

如果我理解你的问题,你需要一个函数来验证选项是否有效。如果是这种情况,您可以通过多种方式执行此操作。这里有两种更简单的方法:

1st:(调用这个函数,看看选项是否有效。函数将return true = valid / false = invalid)

function verifyOptionSelected(option){
    var isValid = false;
    if (option != null){
        switch(option.toLowerCase()){
            case "rock":
            case "paper":
            case "scissor":
                isValid = true;
                break;
            default:
                isValid = false;
        }
    }

    return isValid;
}

第二:(我认为方法相同,但编码方式更好)

function verifyOptionSelected(option){
    var validOptions = ["rock", "paper", "scissor"];
    return option != null && validOptions.indexOf(option.toLowerCase()) >= 0;    
}