逻辑运算符——&&和||

Author Avatar
Emily Chan 5月 02, 2017
  • 在其它设备中阅读本文章

所有的与运算和或运算都可以将值转换为Boolean值再进行运算。

&&与运算

a && b —— 若a能转换为false,则返回a;反之,则返回b。
能转换为false的表达式有:null,0,””,undefined。

a1=true && true       // t && t 结果为 true
a2=true && false      // t && f 结果为 false
a3=false && true      // f && t 结果为 false
a4=false && (3 == 4)  // f && f 结果为 false
a5="Cat" && "Dog"     // t && t 结果为 Dog
a6=false && "Cat"     // f && t 结果为 false
a7="Cat" && false     // t && f 结果为 false

||或运算

a||b —— 若a能转换为true,则返回a;反之,则返回b。

o1=true || true       // t || t 结果为 true
o2=false || true      // f || t 结果为 true
o3=true || false      // t || f 结果为 true
o4=false || (3 == 4)  // f || f 结果为 false
o5="Cat" || "Dog"     // t || t 结果为 Cat
o6=false || "Cat"     // f || t 结果为 Cat
o7="Cat" || false     // t || f 结果为 Cat

参考:
MDN逻辑运算符