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

2022-01-20 00:00:00 conditional-statements javascript

我如何知道 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);

相关文章