如何知道 if 语句中哪个条件为真?

How to know which condition was true in an if statement?(如何知道 if 语句中哪个条件为真?)

本文介绍了如何知道 if 语句中哪个条件为真?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何知道 JavaScript 中 if 语句中的哪个条件为真?

How can I know which condition in an if statement in JavaScript was true?

if(a === b || c === d){ console.log(correctValue) }

我怎么知道它是 a === b 还是 c === d?

How can I know if it was either a === b or c === d?

我想知道除了检查每个条件自己的 if 语句之外是否还有其他方法.

I wanted to know if there was any way of doing this besides checking each condition on it's own if statement.

推荐答案

你不能.
如果它很重要,它需要是两个不同的条件.

You can't.
If it matters, it needs to be two different conditions.

if (a == b) {
  // it was a == b
  return true;
}

if (c == d) {
  // it was c == d
  return true;
}

请注意,即使如此,您也不会知道这两种情况还是只有一种为真.
如果你也想知道这一点,你需要一个额外的 if:

Note that even so, you won't know if both or just one of these conditions is true.
If you want to know this as well, you'll want an additional if:

if (a == b && c == d) {
  // a == b and c == d
} else if (a == b) {
  // just a == b
} else if (c == d) {
  // just c == d
}

return (a == b || c == d);

这篇关于如何知道 if 语句中哪个条件为真?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:如何知道 if 语句中哪个条件为真?

基础教程推荐