![](/img/trans.png)
[英]Why this If statement with OR operation doesn't work in JavaScript?
[英]Why doesn't bitwise xor work in an if statement of JavaScript?
有人可以解釋這種行為嗎?
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);
}
基本上,除非a^b
存儲在變量中(或用括號括起來),否則它將不起作用。
checkSignsWeird(-50,40);
checkSignsWeird(60,70);
兩者產生相同的結果。
艾米,我做錯了還是這是個錯誤? 在if子句中或在其他子句中時,按位運算是否會有所不同? 我不經常使用按位運算,只是覺得這很優雅,所以從這里得到一個答案: 檢查兩個整數是否具有相同的符號
“小於”(<)的優先級高於按位異或(^): https : //developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/Operator_Precedence#Table
您需要用括號將操作分組。
按位運算符的優先級低於比較運算符。 請參閱運算符優先級 。
話雖這么說,不要寫聰明的代碼。
function haveSameSign(a, b) {
return (a >= 0 && b >= 0) || (a < 0 && b < 0);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.