Javascript 无论如何在javascript中实现XOR
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2335979/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is there anyway to implement XOR in javascript
提问by amoran
I'm trying to implement XOR in javascript in the following way:
我正在尝试通过以下方式在 javascript 中实现 XOR:
// XOR validation
if ((isEmptyString(firstStr) && !isEmptyString(secondStr)) ||
(!isEmptyString(firstStr) && isEmptyString(secondStr))
{
alert(SOME_VALIDATION_MSG);
return;
}
Is there a better way to do this in javascript?
有没有更好的方法在 javascript 中做到这一点?
Thanks.
谢谢。
采纳答案by Eineki
I pretend that you are looking for a logical XOR, as javascript already has a bitwise one (^) :)
我假装你正在寻找一个逻辑异或,因为 javascript 已经有一个位 (^) :)
I usually use a simple ternary operator (one of the rare times I use one):
我通常使用一个简单的三元运算符(我很少使用三元运算符之一):
if ((isEmptyString(firstStr) ? !isEmptyString(secondStr)
: isEmptyString(secondStr))) {
alert(SOME_VALIDATION_MSG);
return;
}
Edit:
编辑:
working on the @Jeff Meatball Yang solution
致力于@Jeff Meatball Yang解决方案
if ((!isEmptyString(firstStr) ^ !isEmptyString(secondStr))) {
alert(SOME_VALIDATION_MSG);
return;
}
you negate the values in order to transform them in booleans and then apply the bitwise xor operator. Maybe it is not so maintainable as the first solution (or maybe I'm too accustomed to the first one)
您否定这些值以将它们转换为布尔值,然后应用按位异或运算符。也许它不像第一个解决方案那么易于维护(或者我对第一个解决方案太习惯了)
回答by swestrup
As others have pointed out, logical XOR is the same as not-equal for booleans, so you can do this:
正如其他人指出的那样,逻辑 XOR 与布尔值的不相等相同,因此您可以这样做:
// XOR validation
if( isEmptyString(firstStr) != isEmptyString(secondStr) )
{
alert(SOME_VALIDATION_MSG);
return;
}
回答by Jeff Meatball Yang
You are doing an XOR of boolean values which is easy to model into a bitwise XOR (which Javascript has):
您正在对布尔值进行 XOR,这很容易建模为按位 XOR(Javascript 具有):
var a = isEmptyString(firstStr) ? 1 : 0;
var b = isEmptyString(secondStr) ? 1 : 0;
if(a ^ b) { ... }
回答by CMS
You could use the bitwise XOR operator (^) directly:
您可以^直接使用按位异或运算符 ( ):
if (isEmptyString(firstStr) ^ isEmptyString(secondStr)) {
// ...
}
It will work for your example since the boolean trueand falsevalues are converted into 1and 0because the bitwise operators work with 32-bit integers.
它适用于您的示例,因为布尔值true和false值被转换为1并且0因为按位运算符使用 32 位整数。
That expression will return also either 0or 1, and that value will be coerced back to Boolean by the ifstatement.
该表达式也将返回0or 1,并且该值将被if语句强制回布尔值。
You should be aware of the type coercion that occurs with the above approach, if you are looking for good performance, I wouldn't recommend you to work with the bitwise operators, you could also make a simple function to do it using only Boolean logical operators:
您应该了解上述方法发生的类型强制,如果您正在寻找良好的性能,我不建议您使用按位运算符,您也可以制作一个简单的函数来仅使用布尔逻辑来完成它运营商:
function xor(x, y) {
return (x || y) && !(x && y);
}
if (xor(isEmptyString(firstStr), isEmptyString(secondStr))) {
// ...
}
回答by Nico
Easier one method:
更简单的一种方法:
if ((x+y) % 2) {
//statement
}
assuming of course that both variables are true booleans, that is, 1or 0.
当然,假设两个变量都是真正的布尔值,即1or 0。
- If
x === yyou'll get an even number, so XOR will be0. - And if
x !== ythen you'll get an odd number, so XOR will be1:)
- 如果
x === y你得到一个偶数,那么 XOR 就是0。 - 如果
x !== y那时你会得到一个奇数,那么 XOR 就是1:)
A second option, if you notice that x != yevaluates as a XOR, then all you must do is
第二种选择,如果您注意到x != y计算结果为 XOR,那么您必须做的就是
if (x != y) {
//statement
}
Which will just evaluate, again, as a XOR. (I like this much better)
这将再次评估为 XOR。(我更喜欢这个)
Of course, a nice idea would be to implement this into a function, but it's your choice only.
当然,将其实现为函数是一个不错的主意,但这只是您的选择。
Hope any of the two methods help someone! I mark this answer as community wiki, so it can be improved.
希望这两种方法中的任何一种对某人有所帮助!我将此答案标记为社区维基,因此可以改进。
回答by froadie
Checkout thisexplanation of different implementations of XOR in javascript.
结帐这个在JavaScript XOR的不同实现的解释。
Just to summarize a few of them right here:
在这里总结一下其中的一些:
if( ( isEmptyString(firstStr) || isEmptyString(secondStr)) && !( isEmptyString(firstStr) && isEmptyString(secondStr)) ) {
alert(SOME_VALIDATION_MSG);
return;
}
OR
或者
if( isEmptyString(firstStr)? !isEmptyString(secondStr): isEmptyString(secondStr)) {
alert(SOME_VALIDATION_MSG);
return;
}
OR
或者
if( (isEmptyString(firstStr) ? 1 : 0 ) ^ (isEmptyString(secondStr) ? 1 : 0 ) ) {
alert(SOME_VALIDATION_MSG);
return;
}
OR
或者
if( !isEmptyString(firstStr)!= !isEmptyString(secondStr)) {
alert(SOME_VALIDATION_MSG);
return;
}
回答by Roberto Aloi
Quoting from thisarticle:
引自这篇文章:
Unfortunately, JavaScript does not have a logical XOR operator.
不幸的是,JavaScript 没有逻辑 XOR 运算符。
You can "emulate" the behaviour of the XOR operator with something like:
您可以使用以下内容“模拟”XOR 运算符的行为:
if( !foo != !bar ) {
...
}
The linked article discusses a couple of alternative approaches.
链接的文章讨论了几种替代方法。
回答by Sean
XOR just means "are these two boolean values different?". Therefore:
XOR 只是意味着“这两个布尔值不同吗?”。所以:
if (!!isEmptyString(firstStr) != !!isEmptyString(secondStr)) {
// ...
}
The !!s are just to guarantee that the !=operator compares two genuine boolean values, since conceivably isEmptyString()returns something else (like nullfor false, or the string itself for true).
该!!s为只是为了保证!=运营商比较两个真正的布尔值,因为可以想象isEmptyString()返回别的东西(如null虚假,或字符串本身真正的)。
回答by Butshuti Hakiza
Assuming you are looking for the BOOLEAN XOR, here is a simple implementation.
假设您正在寻找 BOOLEAN XOR,这里是一个简单的实现。
function xor(expr1, expr2){
return ((expr1 || expr2) && !(expr1 && expr2));
}
The above derives from the definition of an "exclusive disjunction" {either one, but not both}.
以上源自“排他性析取”的定义{一个,但不是两个}。
回答by Brian North
Since the boolean values trueand falseare converted to 1and 0respectively when using bitwise operators on them, the bitwise-XOR ^can do double-duty as a logical XOR as well as a bitwiseone, so long as your values are boolean values (Javascript's "truthy" values wont work). This is easy to acheive with the negation !operator.
由于布尔值true和false在对它们使用按位运算符时分别转换为1和0,因此按位异或^可以作为逻辑异或和按位执行双重任务,只要您的值是布尔值(Javascript 的“真实”值行不通)。使用否定!运算符很容易实现这一点。
a XOR bis logially equivalent to the following (short) list of expressions:
a XOR b在逻辑上等同于以下(短)表达式列表:
!a ^ !b;
!a != !b;
There are plenty of other forms possible - such as !a ? !!b : !b- but these two patterns have the advantage of only evaluating aand bonce each (and will not "short-circuit" too if ais false and thus not evaluate b), while forms using ternary ?:, OR ||, or AND &&operators will either double-evaluate or short-circuit.
还有很多其他可能的形式 - 例如!a ? !!b : !b- 但这两种模式的优点是只评估a和b一次(如果a为假,也不会“短路” ,因此不评估b),而使用三元的形式?:,或||,或 AND&&运算符将进行双重评估或短路。
The negation !operators in both statements is important to include for a couple reasons: it converts all "truthy" values into boolean values ( "" -> false, 12 -> true, etc.) so that the bitwise operator has values it can work with, so the inequality !=operator only compares each expression's truth value (a != bwould not work properly if aor bwere non-equal, non-empty strings, etc.), and so that each evaluation returns a boolean value result instead of the first "truthy" value.
这!两个语句中的否定运算符很重要,原因有几个:它将所有“真实”值转换为布尔值(“” -> false,12 -> true 等),以便按位运算符具有可以工作的值,所以不等式!=运算符只比较每个表达式的真值(a != b如果a或b不等,非空字符串等,则无法正常工作),因此每个评估都返回一个布尔值结果而不是第一个“真值”价值。
You can keep expanding on these forms by adding double negations (or the exception, !!a ^ !!b, which is still equivalent to XOR), but be careful when negating just part of the expression. These forms may seem at first glance to "work" if you're thinking in terms of distribution in arithmatic (where 2(a + b) == 2a + 2b, etc.), but in fact produce different truth tables from XOR (these produce similar results to logical NXOR):
您可以通过添加双重否定(或例外,!!a ^ !!b,仍然等同于 XOR)来继续扩展这些形式,但在否定表达式的一部分时要小心。如果您考虑算术分布( where2(a + b) == 2a + 2b等),这些形式乍一看似乎“有效” ,但实际上从 XOR 产生不同的真值表(这些产生与逻辑 NXOR 相似的结果):
!( a ^ b )
!( !!a ^ !!b )
!!a == !!b
The general form for XOR, then, could be the function (truth table fiddle):
那么,异或的一般形式可以是函数(真值表小提琴):
function xor( a, b ) { return !a ^ !b; }
And your specific example would then be:
然后你的具体例子是:
if ( xor( isEmptyString( firstStr ), isEmptyString( secondStr ) ) ) { ... }
Or if isEmptyStringreturns only boolean values and you don't want a general xorfunction, simply:
或者,如果isEmptyString只返回布尔值并且您不需要通用xor函数,只需:
if ( isEmptyString( firstStr ) ^ isEmptyString( secondStr ) ) { ... }

