简体   繁体   English

为什么按位异或在JavaScript的if语句中不起作用?

[英]Why doesn't bitwise xor work in an if statement of JavaScript?

Could somebody explain this behavior? 有人可以解释这种行为吗?

https://jsfiddle.net/td1qtyxL/9/ https://jsfiddle.net/td1qtyxL/9/

function checkSignsWeird(a,b){
    var output = "";
    if(a^b < 0){
        output = "The "+a+" and "+b+" have DIFFERENT signs.";
    }else{
        output = "The "+a+" and "+b+" have the SAME sign.";
    }
    console.log(output);
}

Basically unless a^b is stored in a variable (or wrapped in parentheses), it doesn't work. 基本上,除非a^b存储在变量中(或用括号括起来),否则它将不起作用。

checkSignsWeird(-50,40);
checkSignsWeird(60,70);

Both produce the same result. 两者产生相同的结果。

Amy I doing something wrong or is this a bug? 艾米,我做错了还是这是个错误? Does bitwise work differently when it's in an if clause or when it's elsewhere? 在if子句中或在其他子句中时,按位运算是否会有所不同? I don't often work with bitwise, just thought this was elegant, following up on an answer from here: Check if two integers have the same sign 我不经常使用按位运算,只是觉得这很优雅,所以从这里得到一个答案: 检查两个整数是否具有相同的符号

The "Less Than" (<) has a higher precedence than the bitwise XOR (^): https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence#Table “小于”(<)的优先级高于按位异或(^): https : //developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/Operator_Precedence#Table

You need to group the operation with parentheses. 您需要用括号将操作分组。

Bitwise operators have a lower precedence than comparison operators. 按位运算符的优先级低于比较运算符。 See Operator precedence . 请参阅运算符优先级

That being said, don't write clever code. 话虽这么说,不要写聪明的代码。

function haveSameSign(a, b) {
    return (a >= 0 && b >= 0) || (a < 0 && b < 0);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM