Logical operators(邏輯運算子)
&& (And)
每項皆需符合true才成立
var x = 5;
var y = 10;
(x >= 5) && (y <= 10); //true
|| (Or)
只要一邊是true即可成立
var x = 5;
var y =10;
(x == 6) || (y>0); //true
! (Not)
做反向的意思,true變為false,反之亦然。
var x = 5;
var y =10;
!(x < 4); //true
實戰測驗一下:
var x = 5;
var y = 10;
!(x >= y && y == 8) || (y != 10)
拆解:
01
!(x >= y && y == 8)
x >= y //false
y == 8 //false
(x >= y && y == 8) //false
!(x >= y && y == 8) //true
02
(y != 10) //false
03
一邊是true一邊是false,加上||(只要一邊符合true即可),故最終答案為true!
!(x >= y && y == 8) || (y != 10) //true
Truthy&Falsy(真值與假值)
In JavaScript, a truthy value is a value that is considered true when encountered in a Boolean context. — MDN Web Docs
A falsy (sometimes written falsey) value is a value that is considered false when encountered in a Boolean context. — MDN Web Docs
Truthy是遇到Boolean context時會被視為true的值,而Falsy是遇到Boolean context時會被視為false的值。
Falsy
Javascript中為Falsy的值有以下:
1. 0、-0、+0、NaN
2. null、undefined
3. ""(Empty String)
4. false(boolean)
Truthy
不在Falsy中的其他值皆可歸類到Truthy,例如:
1. []
2. {}
3. "false"
4. "0"
5. " "
6. Infinity
7. function(){}
實戰測驗一下:
var a = ""
var b = 8
var c = "0"
!(c >= 0 || a == false) && (b !== "8")
拆解:
01
!(c >= 0 || a == false)
c >= 0 //true
a == false //true
(c >= 0 || a == false) //true
!(c >= 0 || a == false) //false
02
(b !== "8") //true
03
!(c >= 0 || a == false) && (b !== "8") //false
不清楚等號比較運算子(==)、(===)用法的人可看筆記第二篇,有詳細的介紹。
參考資料: