Operatory logiczne JavaScript i wyniki
Wiem, że wynik operacji logicznych w większości języków jest prawdziwy, fałszywy lub 1,0. W Javascript próbowałem:
alert(6||5) // => returns 6
alert(5||6) // => returns 5
alert(0||5) // => returns 5
alert(5||0) // => returns 5
alert(5||1) // => returns 5
alert(1||5) // => returns 1
alert(5&&6) // => returns 6
alert(6&&5) // => returns 5
alert(0&&5) // => returns 0
alert(5&&0) // => returns 0
alert(-1&&5) // => returns 5
alert(5&&-1) // => returns -1
Więc jaki jest wynik operatorów logicznych? Jeśli jeden operand ma wartość 0 lub 1, działa zgodnie z oczekiwaniami. Jeśli oba są niezerowe i inne niż 1 to
W przypadku logicznegoor
, zwracany jest pierwszy operandW przypadku logicznegoand
, drugi argument jest zwracanyCzy to jest ogólna zasada?
Inną rzeczą, której nie wiem, jest operator|
.
Próbowałem operatora|
i otrzymałem różne wyniki:
alert(5|8) // => returns 13
alert(8|5) // => returns 13
alert(-5|8) // => returs -5
alert(8|-5) // => returns -5
alert(0|1) // => returns 1
alert(1|0) // => returns 1
alert(1|1) // => returns 1
Co właściwie robi ten operator?