Tuesday, November 22, 2016

javascript '||'、'&&'

由于javascript是弱类型语言,所以在javascript中这两个表达式可能跟其他语言(比如java)中不太一样。
在javascript中,“&&”运算符运算法则如下:
如果&&左侧表达式的值为真值,则返回右侧表达式的值;否则返回左侧表达式的值。
||”运算符的运算法则如下:
如果||左侧表达式的值为真值,则返回左侧表达式的值;否则返回右侧表达式的值。

Source@0

The && and || operators use short-circuit logic, which means whether they will execute their second operand is dependent on the first. This is useful for checking for null objects before accessing their attributes:

var name = o && o.getName();
Or for setting default values:
var name = otherName || "default";
JavaScript has a ternary operator for conditional expressions:
var allowed = (age > 18) ? "yes" : "no";

@reference_1_mozilla

No comments:

Post a Comment