[英]Javascript logical operators and results
我知道大多數語言中邏輯運算的結果是true,false或1,0。 在Javascript中我嘗試了以下內容:
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
那么邏輯運算符的結果是什么? 如果一個操作數為0或1,則它按預期工作。 如果兩者都非零而不是1
or
情況下,返回第一個操作數 and
情況下,返回第二個操作數 這是一般規則嗎?
我不知道的另一件事是操作員|
。
我試過運算符|
得到了不同的結果:
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
這個運營商實際上做了什么?
由於javascript不是類型化的語言,因此任何對象都可以在邏輯運算符上使用,如果此對象為null,則為false boolean,空字符串,0或未定義的變量,如果它是其他任何內容,則它就像false
一樣然后它就像一個true
在邏輯運算結束時,返回最后一個檢查值。
所以
6 || 2
Check first value -> "6"
6 = true
Go to next value -> "2"
2 = true
操作結束,返回最后一個值。
2如果傳遞給另一個邏輯操作,它將與true相同。
編輯:那是一個錯誤的陳述。 6||2
返回6
因為6
作為true
就足以知道條件OR
是真的而無需檢查下一個值。
它實際上和中國一樣
真真正||
Check first value -> "true"
Check next value -> "true"
return last value -> "true"
對於6 && 0 && 2
First value 6 = true
Next value 0 = false
在此處停止操作並返回上次檢查的值:0。
| 運算符是一個完全不同的東西,它簡單地對輸入值的位進行邏輯或運算,正如akp在另一個答案中所解釋的那樣。
實際上你得到的是純粹的數字結果......就像......
3 in binary is 011......
4 in binary is 100.....
when u perform 3|4......
it is equivalent to 011|100......i.e the OR operator which is the one of the bases of all logical operations
011
100
will give 111 ie 7.............
so u will get 3|4 as 7......
hope u understand..
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.