首页 > 解决方案 > 我可以在这里使用 if else 语句吗?

问题描述

我正在构建一个琐事游戏,它有一个游戏完成屏幕,显示你的表现如何。它说"You got __ out of __ right"(例如:正确的 8 个中的 6 个)并且代码如下所示:

function displayThankyou() {
  $(".screen").hide();
  $("#thankyou-screen").show();
  $("#game-results").html(
    `You got ${trivia.totalCorrect} of ${trivia.totalAnswered} correct.`
  );
}

如果我想在该人在游戏中表现出色时显示不同的信息,例如 6 对或更好:“你做得很好!” 或者如果他们做得不好,5 对或更少:“下次好运。”,我是否使用 if else 来做到这一点?

标签: javascriptif-statement

解决方案


@Chad Roussel,是的,您可以为此使用“if-else”语句。例如(纯 JS):

//initialise variables correct and total
var correct = trivia.totalCorrect;
var total = trivia.totalAnswered;

//if statement
if (correct >= 6){
     //log to user their "greatness."
     console.log("You did great!");
}else{
     console.log("You didn't get a 6/8. Try again");
}

检查https://www.w3schools.com/js/js_if_else.asp以获取有关 if-else 语句的更多信息!

编辑:正如其他人所提到的,您可以使用 switch-case 解决方案。但是,我发现两者之间没有任何好处。做对你有用的事!


推荐阅读