Javascript 速记 - '||' 是什么意思 在作业中使用时的运算符均值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4511301/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 13:57:34  来源:igfitidea点击:

Javascript Shorthand - What Does the '||' Operator Mean When Used in an Assignment?

javascript

提问by Jim G.

I just took a look at this answer, and I noticed the following line of javascript code:

我只是看了一下这个答案,我注意到了下面这行 javascript 代码:

hrs = (hrs - 12) || 12;

My Question:

我的问题:

What does the '||' operator mean when used in an assignment?

'||' 是什么意思 运算符在赋值中使用时是什么意思?

采纳答案by nsdel

In this case, the code assigns 12 to hrs if hrs-12 = 0 (as JavaScript sees it, 0 = false).

在这种情况下,如果 hrs-12 = 0(如 JavaScript 所见,0 = false),则代码将 12 分配给 hrs。

More generally, it assigns the latter value to the variable if the former value evaluates to 0, the empty string, null, undefined, etc.

更一般地,如果前一个值的计算结果为 0、空字符串、null、未定义等,它会将后一个值分配给变量。

回答by álvaro González

It always means the same: logical OR

它总是意味着相同:逻辑或

It's a common trick that makes use of type casting. Many non-boolean expressions evaluate to false. It's the same as this:

这是使用类型转换的常见技巧。许多非布尔表达式的计算结果为假。它与此相同:

hrs = (hrs-12)
if(!hrs){
    hrs = 12;
}

And the if() works because 0 casts to false. It's also used to deal with undefined variables:

并且 if() 起作用是因为 0 转换为 false。它还用于处理未定义的变量:

function foo(optionalValue){
    var data = optionalValue || "Default value";
}
foo();
foo("My value");

回答by meder omuraliev

In the case of if hrs-12evaluates to 0, the person wants hrsto be assigned 12since 0is not suitable.

在 ifhrs-12评估为的情况下0,该人因不适合而希望hrs被分配。120

Since 0evaluates to false, the expression becomes false || 12, in which case 12would be chosen since it's truthy.

由于0评估为假,表达式变为false || 12,在这种情况下12将被选择,因为它是真的。

回答by Spudley

It means "If the first half of the expression is false, then use the second half instead."

它的意思是“如果表达式的前半部分为假,则使用后半部分代替。”

Practically in this example, it means that hrswill be set to hours-12, unless hours-12is zero, in which case it will hrswill be set to 12.

实际上在这个例子中,这意味着hrs将被设置为hours-12,除非hours-12为零,在这种情况下它将hrs被设置为12

回答by tszming

It means if hrs - 12 is evaluated to false (false, null, undefined, NaN, '', 0), then 12 will be assigned to hrs.

这意味着如果 hrs - 12 被评估为 false (false, null, undefined, NaN, '', 0),那么 12 将被分配给 hrs。

回答by Flexo

It means "short circuit or". I.e. if the first part of the expression is false use the second instead. Wikipedia has an articleon this with syntax for a number of languages.

意思是“短路或”。即,如果表达式的第一部分为假,请改用第二部分。维基百科有一篇关于此的文章,其中包含多种语言的语法。