How to know which condition was true in an if statement?

故事扮演 提交于 2019-11-30 09:47:52

问题


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

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

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

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


回答1:


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;
}

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



回答2:


If you really need to know which condition was true, just test them separately:

if(a == b) {
    console.log("a == b");
    return true; 
} else if(c == d) {
    console.log("c == d");
    return true; 
}

Alternatively, you might prefer something like this:

var result;
if ((a == b && result = "a == b") || (c == d && result = "c == d")) {
    console.log(result);
    return true;
}

This code is effectively equivalent to the former, however, I wouldn't recommend using this in a production system. It's much harder to read and guess the original intent of the code—it's likely that the person reading this after you would think the result = was supposed to be result ==. Also note that because empty strings are falsy, you must ensure that the string you assign to result is never empty, otherwise it would never enter the if-block.



来源:https://stackoverflow.com/questions/21268364/how-to-know-which-condition-was-true-in-an-if-statement

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!