如何检查并列出 if 语句中的所有错误条件 - JavaScript?

How to check and list all false conditionals in if statement - JavaScript?

我正在努力改进我的代码并获得更好的日志记录。

是否有一种理想的方法来判断条件列表中哪些条件为假?

即)

if(isAnimal && isCarnivore && isPlant){
 // does something
} else {
 // want to console.log all the false conditions in one console.log
}

我们可以写

let falseString = ""


if (!isAnimal) {
 falseString = falseString + "is not an Animal";
} 

if (!isCarnivore) {
 falseString = falseString + "is not a Carnivore";
}

if (!isPlant) {
 falseString = falseString + "is not a Plant";
}

console.log("string of false conditions" , falseString)

然后这将记录一个条件为假的字符串,但这似乎是一个幼稚的解决方案。

在 JavaScript 中执行此操作的更好方法是什么?

谢谢!

如果变量是全局声明的,你可以将它们的名称存储在一个数组中,并通过引用window对象来检查它是否是true

let falseString = ""

isAnimal = true
isCarnivore = false
isPlant = false

const booleans = ['isAnimal', 'isCarnivore', 'isPlant'];

const falseBooleans = booleans.filter(e => !window[e])

console.log(falseBooleans)

您可以通过创建答案对象然后对其进行迭代来实现自动化

// Create object for answers
const answers = {};

// Alter object with answers...
answers.isAnimal = false;
answers.isCarnivore = false;
answers.isPlant = false;
answers.isHuman = true;
answers.isMineral = false;
answers.isInsect = false;

// Define result strings
let falseAnswers = "False answers is:";
let trueAnswers = "True answers is:";

// Loop answers
for(const answer in answers) {
  answers[answer] ? trueAnswers += ` ${answer}` : falseAnswers += ` ${answer}`;
}

// Log
console.log(trueAnswers);
console.log(falseAnswers);