简体   繁体   English

将if语句转换为三元运算符

[英]Convert if statement to ternary operator

I tried to convert these if statement to ternary: 我试图将这些if语句转换为三元:

var eatsPlants = false;
var eatsAnimals = true;

    if(eatsPlants){
      return 'herbivore';
    }else if(eatsAnimals){
      return 'carnivore';
    }else if(eatsPlants && eatsAnimals){
    return 'omnivore';
    }else{
     return undefined;
    }

Here's my solution: 这是我的解决方案:

var category = eatsPlants && eatsAnimals ? "omnivore" : "herbivore" : "carnivore" : undefined;

console.log(category);

But this doesnt work and it returns the error missing semicolon. 但这不起作用,它返回错误的分号。

Any idea how to fix it? 知道如何解决吗?

You forgot the other two conditions, and changed the order of checks (which is actually necessary to make it work, though). 您忘记了其他两个条件,并更改了检查顺序(尽管这实际上是使其工作所必需的)。 You'd do either 你要么做

return (eatsPlants && eatsAnimals
  ? 'omnivore'
  : (eatsPlants
    ? 'herbivore'
    : (eatsAnimals
      ? 'carnivore'
      : undefined)));

or, avoiding the AND operation by nesting, 或者,通过嵌套避免AND操作,

return (eatsPlants
  ? (eatsAnimals
    ? 'omnivore'
    : 'herbivore')
  : (eatsAnimals
    ? 'carnivore'
    : undefined));

(The parenthesis and indentation are optional, but strongly encouraged for readability, at least one of them). (括号和缩进是可选的,但出于可读性考虑,强烈建议至少使用其中之一)。

You should add the remaining if conditions too if条件也应该添加其余的

var category = eatsPlants && eatsAnimals ? "omnivore" : eatsPlants? "herbivore" : eatsAnimals? "carnivore" : undefined;

console.log(category);

The js snippet shared by you may throw an error as return statement is not inside a function. 您共享的js代码段可能会引发错误,因为return语句不在函数内部。

Have created one more variable returnResult which will be assinged with new value depending on the condition. 已经创建了另一个变量returnResult ,该变量将根据条件使用新值进行赋值。

!1 is false & !0 is true, void 0 is undefined !1为假&!0为真,void 0未定义

var eatsPlants = !1, eatsAnimals = !0, returnResult = "";
returnResult = eatsPlants ? "herbivore" : eatsAnimals ? "carnivore" : eatsPlants && eatsAnimals ? "omnivore" : void 0;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM