Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
470 views
in Technique[技术] by (71.8m points)

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...