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
142 views
in Technique[技术] by (71.8m points)

How to xor three variables in javascript?

Related to my original question, how would you xor three boolean variables in javascript. One variable can be true the rest must be false.

This is my solution, but I feel there is a better one:

function isValid(a, b, c) {
  return (a !== b ! == c) && [a, b, c].includes(false);
}

I've gotten some feed back from the comments, let me define what I'm asking (sorry for all the confusion).

  1. I'm actually doing this in a typescript class. I figured I'd just remove the method and make it a classless function. I realize now that this does affect the solution. Sorry about that.

  2. I suppose I must have missused the term XOR. What I'm trying to say is, only a OR b OR c can be true, and one of them must be true. I hope that is more clear.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

If these are boolean values, just filter and test that only one is true:

function isValid(...args) {
  return args.filter(v => v).length == 1;
}

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

...