javascript var x = x || 是什么意思 {};
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3563153/
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
What does var x = x || {} ;
提问by jakoh
what does the following code do in java script:
下面的代码在java脚本中做了什么:
var x = x || {};
回答by jAndy
||is the logical OR.
||是合乎逻辑的OR。
The expression
表达方式
var x = x OR {};
should become more obvious then.
应该会变得更加明显。
If xhas a falsyvalue (like null, undefined, 0, ""), we assign xan empty object {}, otherwise just keep the current value. The long version of this would look like
如果x有一个假值(如null, undefined, 0, ""),我们分配x一个空对象{},否则只保留当前值。这个的长版本看起来像
var x = x ? x : {};
回答by Gabe
If xis undefined (or null, or any other falsevalue), it becomes an empty object.
如果x未定义(或 null,或任何其他false值),则它成为一个空对象。
回答by Dzhaughn
One should never write "var x = x || {};" per se.
永远不要写“var x = x || {};” 本身。
The only circumstance where this is not identical to "var x = {};" is when x was previously initialized in the same scope. That is immoral. Note:
这与“var x = {};”不同的唯一情况 是当 x 先前在同一范围内初始化时。那是不道德的。笔记:
function() {
x = {foo:"bar"};
var x = x || {};
}
Is the same as, merely more confusing than,
是一样的,只是比,更令人困惑,
function() {
var x = {foo:"bar"};
x = x || {};
}
In neither case is there any reference to the value of the symbol "x" in the global scope.
在这两种情况下,全局范围内都没有对符号“x”的值的任何引用。
This expression is a confused variant of the legitimate lazy property initialization idiom:
这个表达式是合法的惰性属性初始化习惯用法的一个混淆变体:
function( foo ) {
foo.x = foo.x || {};
foo.x.y = "something";
}
回答by Darin Dimitrov
Assign xto a new empty object if it is null(undefined, false) or keep it's existing value if not null.
x如果它是null(undefined, false),则分配给一个新的空对象,如果不是,则保留它的现有值null。
回答by Senthil Kumar Bhaskaran
unless x is defined or assigned a value it will take empty object as default value..
除非 x 被定义或分配了一个值,否则它将把空对象作为默认值..
that is,
那是,
for example
x = 10
var x = x || {};
output must be
输出必须是
10
if x value not assigned. the output value must be,
如果未分配 x 值。输出值必须是,
undefined
回答by Anil Soman
if var x is defined then it will be that defined value. Else it will be empty object like [object Object]
如果定义了 var x,那么它将是那个定义的值。否则它将是空对象,例如[object Object]
For example, in the following code block, x will be 10:
例如,在以下代码块中,x 将为10:
var x = 10;
x = x || {}
However, if:
但是,如果:
var x = x || {};
then xwill be [object Object]
然后x将是[object Object]

