简体   繁体   English

如何|| (OR)操作员在作业中的工作

[英]How does the || (OR) operator work in assignments

What does it mean when you use the || 使用||时意味着什么 operator to define a variable like 运算符定义变量之类的

 mouse.x = e.clientX || e.pageX; 

What is the operator used for? 操作员使用的是什么?

Using this operator in the way you show sets the var to the second value if the first one is falsy . 如果第一个值是假的,则以您显示的方式使用此运算符将var设置为第二个值。

In your specific example it is a shortcut for 在您的具体示例中,它是一个快捷方式

if (e.clientX) mouse.x = e.clientX;
else mouse.x = e.pageX

to avoid accessing e.clientX twice: If clientX is not set, take pageX. 避免两次访问e.clientX:如果未设置clientX,请使用pageX。

More information about this Logical Operator from MDN : 有关MDN逻辑运算符的更多信息:

Logical operators are typically used with Boolean (logical) values. 逻辑运算符通常与布尔(逻辑)值一起使用。 When they are, they return a Boolean value. 如果是,则返回布尔值。 However, the && and || 但是,&&和|| operators actually return the value of one of the specified operands, so if these operators are used with non-Boolean values, they may return a non-Boolean value. 运算符实际上返回其中一个指定操作数的值,因此如果这些运算符与非布尔值一起使用,则它们可能返回非布尔值。

 var e = { "clientX":25,"pageX":35 } var res = e.clientX || e.pageX; // 25 console.log(res); e = { "clientX":0,"pageX":35 } res = e.clientX || e.pageX; // 35, clientX is falsy console.log(res) e = { "clientX":0,"pageX":0 } res = e.clientX || e.pageX; // 0 from pageX, clientX is falsy console.log(res) e = { "clientX":0,"pageX":null } res = e.clientX || e.pageX; // null from pageX, clientX is falsy console.log(res) 

|| is the logical OR operator. 是逻辑OR运算符。 It is used when more than one statement may be considered. 当一个以上的声明被视为时使用。

if (age > 18 || hasParentalSignature == true) {
    // Allowed to attend
}

In Javascript the operator also serves as a Null Coalescing Operator . 在Javascript中,运算符也可用作Null Coalescing Operator It is not strictly null coalescing, because it recognizes "falsy" values other than null , but it is very similar. 它不是严格的空合并,因为它识别除null之外的“假”值,但它非常相似。

Null coalescing is a "if value A is falsy then use B instead" operator. 空结合是“如果值A是假的,那么使用B代替”运算符。 For example: 例如:

var x = "Hello!";
var z = y || x;

In this example the y variable was never defined, which means that it is "falsy", so instead the x variable will be used. 在这个例子中, y变量从未被定义,这意味着它是“虚假的”,因此将使用x变量。

Using if statements it would be the same as: 使用if语句将与以下内容相同:

var x = "Hello!";
if (y) {
    var z = y;
} else {
    var z = x;
}

Or using the ternary operator: 或使用三元运算符:

var x = "Hello!";
var z = (y ? y : x);

Most other languages, that have a null coalescing operator, use a dedicated operator to do this. 大多数其他具有空合并运算符的语言使用专用运算符来执行此操作。 In Javascript, for whatever reason, it is part of the OR operator. 在Javascript中,无论出于何种原因,它都是OR运算符的一部分。

This question deals with the OR's null coalescing properties. 这个问题涉及OR的空合并属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM