具有多个语句的三元运算符

时间:2017-11-11 04:26:20

标签: javascript ternary-operator

/ *  *使用一系列三元运算符将类别设置为以下之一:  * - "草食动物"如果动物吃植物  * - "食肉动物"如果动物吃动物  * - "杂食动物"如果动物吃植物和动物  * - 如果动物不吃植物或动物,则不确定  *  *备注  * - 在三元表达式中使用变量eatsPlantseatsAnimals  * - if语句不允许;-)  * /

我使用了这段代码,但它没有把事情搞定

  var eatsPlants = true;
var eatsAnimals = false;


var category = eatsPlants ? "herbivore" : "carnivore";
console.log(category);
var category = (eatsPlants && eatsAnimals) ? "omnivore" : "undefined";
console.log(category);

解决这个问题的任何想法

3 个答案:

答案 0 :(得分:2)

这将有效 -

const category = (eatPlants && eatAnimals) ? 'omnivore' : eatAnimals ? 'carnivore' : eatPlants ? 'herbivore' : undefined;

如果您希望使用三元运算符绘制if-else分支,则需要将一个三元组的其他部分链接到另一个三元组等等。

但我建议,如果其他分支保持代码的可读性,你就会使用它。三元组只是在多种条件下弄得一团糟。

这在if-else逻辑中有多清楚。

let category = undefined;
if (eatPlants && eatAnimals)
     category = 'omnivore';
else if (eatPlants)
     category = 'herbivore';
else if (eatAnimals)
     category = 'carnivore';

答案 1 :(得分:1)

这可以解决您的问题。

var eatsPlants = false;
var eatsAnimals = true;

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

console.log(category);

答案 2 :(得分:0)

var eatsPlants = false;
var eatsAnimals = false;

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

console.log(category);
相关问题