【问题标题】:How to check and list all false conditionals in if statement - JavaScript?如何检查并列出 if 语句中的所有错误条件 - JavaScript?
【发布时间】:2021-11-20 02:04:02
【问题描述】:

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

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

即)

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 中执行此操作的更好方法是什么?

谢谢!

【问题讨论】:

  • Code Review 是更多基于意见的问题的地方。也就是说,您可以只写console.log(isAnimal) 等等,而不必为每个可能的条件和变量组合编写和连接一个字符串。
  • 谢谢。是的,这很好,但在这种情况下,我需要将结果放在一个字符串中,而不是在单独的控制台日志中
  • 你能详细说明记录的目的吗?是用于调试还是保存到日志文件以供以后查看?目的极大地影响了可以被认为更好/更有效/等的东西。简而言之:您想要完成的改进是什么?
  • @Philip 目的是为了调试。所以可以跟踪,哪些条件是假的,所以我们知道哪些条件是假的,以及为什么代码进入 else case 而不是 true 分支
  • 那么我建议使用一个全局定义的对象,其中包含所有布尔值。这样你就可以用一个简短的语句console.log他们,并且仍然可以在输出中一次看到所有内容。

标签: javascript string if-statement boolean conditional-statements


【解决方案1】:

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

// 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);

【讨论】:

    【解决方案2】:

    如果变量是全局声明的,您可以将它们的名称存储在一个数组中,并通过引用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)

    【讨论】:

    • 谢谢,只有与前端相关联的窗口才有效?我只是在后端写这些,所以它没有附加到任何窗口/浏览器?
    • @Suzy 你能解释一下你所说的后端是什么意思吗?你在用 NodeJS 吗?如果是这样,它应该仍然有效。
    • 谢谢,过滤是个好主意。我正在使用 webdriverIo,它说没有定义窗口?
    • @Suzy 试试代码,变量可能默认是全局的。
    • 是的,我尝试运行代码,但它仍然在 cmd 中显示“未定义窗口”我也安装了 npm
    猜你喜欢
    • 2021-09-29
    • 1970-01-01
    • 2022-01-15
    • 1970-01-01
    • 2023-01-11
    • 1970-01-01
    • 2017-12-08
    • 1970-01-01
    • 2020-01-15
    相关资源
    最近更新 更多