When used with Boolean operands, the || operator performs the Boolean OR operation on the two values: it returns true if either the first operand or the second operand is true, or if both are true. If both operands are false, it returns false.
All know the above usage, but I mention the following usage:
An idiomatic usage of this operator is to select the first value in a set of alternatives that is defined and non-null (that is, the first value that does not convert to false). Here is an example:
// If max_width is defined, use that. Otherwise look for a value in // the preferences object. If that is not defined use a hard-coded constant. var max = max_width || preferences.max_width || 500;
本文介绍了JavaScript中逻辑或(||)运算符的两种使用方式:进行布尔操作及选取第一个定义且非空值。通过示例代码展示了如何根据不同条件选择使用预定义值、配置对象中的值或默认值。
790

被折叠的 条评论
为什么被折叠?



