首页 > 解决方案 > 有人可以帮我理解这个代码逻辑,它是如何工作的吗?

问题描述

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

//我不明白它是如何检查多个事物的代码

标签: javascript

解决方案


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

嗯,这和

if(eatsPlants)
  if(eatsAnimals) category = "omnivore";
  else category = "herbivore";
else 
  if(eatsAnimals) category = "carnivore";
  else category = "undefined";

该条件运算符的结构如下:

(condition) ? (outcome if condition is true) : (outcome if condition is false)

推荐阅读