-4

我正在与三元运算符一起工作,我需要一些帮助。我正在转换一个简单的 if-else 语句,但我有一个简单的语法错误,我似乎无法弄清楚。我正在练习代码学院的练习,但我得到的错误是第一行未定义。这是原始代码:

if (food === "taco") {
  foodType = "Mexican";
} else {
  foodType = "other";  
}

这是我的代码。第一行是未定义的,但我似乎无法弄清楚如何。

var food = prompt("Food type");
var food === "taco" ? "Mexican": "other";
4

3 回答 3

7

我想你的意思是:

foodType = (food === "taco") ? "Mexican": "other"
                   ^condition       ^true    ^false

MDN:条件运算符

于 2012-10-29T05:46:29.840 回答
1

三元语法应该是这样的,

variableToBeSet = (condition) ? trueValue : falseValue;

在你的问题中,

foodtype = (food === "taco") ? "Mexican": "other";
于 2012-10-29T05:47:10.167 回答
0

布尔表达式 ? 值1:值2

例如,下面的 if..then..else 语句

boolean isSmiley = true;

 String mood = "";

 if (isSmiley == true)
 {
   mood = "I'm Happy!";
 }
 else
 {
   mood = "I'm Sad!";
 }

现在您可以使用如下所示的三元选项

 boolean isSmiley = true;
 String mood = (isSmiley == true)?"I'm Happy!":"I'm Sad!"; 
于 2012-10-29T05:49:56.707 回答