此 Javascript 行中的两个管道符号 (OR)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10358823/
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
Two pipe symbols (OR) in this Javascript line
提问by benhowdle89
Possible Duplicate:
What does “options = options || {}” mean in Javascript?
I have seen this in JS:
我在 JS 中看到过这个:
item = item || {};
I'm guessing it's some variation of a ternary operator but what does is actually do?
我猜这是三元运算符的一些变体,但实际上是做什么的?
回答by ajax333221
(expr1 || expr2)
"Returns expr1 if it can be converted to true; otherwise, returns expr2."
“如果可以转换为真,则返回 expr1;否则,返回 expr2。”
So when expr1
is (or evaluates to) one of these 0,"",false,null,undefined,NaN
, then expr2
is returned, otherwise expr1
is returned
所以当expr1
是(或评估为)其中之一时0,"",false,null,undefined,NaN
,则expr2
返回,否则expr1
返回
回答by Niet the Dark Absol
It's called redundancy, but in this case it's a good thing. Basically, if item
is not defined (or otherwise falsy (false
, 0
, ""
...), then we give it a default value.
这被称为冗余,但在这种情况下,这是一件好事。基本上,如果item
未定义(或以其他方式为假(false
, 0
, ""
...),那么我们给它一个默认值。
Most common example is in events:
最常见的例子是在事件中:
evt = evt || window.event;
回答by Dhaivat Pandya
If item exists, set item to item, or set it to {}
如果 item 存在,则将 item 设置为 item,或者将其设置为 {}
回答by Mark Kahn
It equates to:
它相当于:
if( !item ){ item = {}; }