如何知道if语句中哪个条件成立? [英] How to know which condition was true in an if statement?

查看:112
本文介绍了如何知道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语句中哪个条件成立?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆