'var a = a ||的目的是什么? {b:1}'语法 [英] What is a purpose of 'var a = a || { b : 1}' syntax
问题描述
我想知道更长的时间以下是什么意思:
I was wondering for a longer time what the below means:
var a = a || { b : 1 }
如果'a'之前分配了任何属性......他们消失了。那么上面语法的目的是什么?
if 'a' had any properties assigned before... they dissapear. So what is a purpose of the above syntax ?
推荐答案
我喜欢这种语法。在我看来,它非常优雅。
I love this kind of syntax. In my opinion, it is very elegant.
解释相当简单。你在这里有一个使用 ||
(或)运算符的条件表达式。这将根据条件的结果为变量赋值。
The explanation is fairly simple. What you have here is a conditional expression using the ||
(or) operator. This will assign a value to the variable according to the result of the conditional.
在这种情况下,条件是 a || {b:1}
,所以如果已经定义了变量 a
(即不等于假值),那么变量 a
将保持不变。但是,如果尚未定义 a
,则会为其分配对象文字的值 {b:1}
。
In this case, the condition is a || { b : 1 }
, so if the variable a
has already been defined (i.e. not equal to a false value), then the variable a
will be left unchanged. However if a
has not been defined yet, then it will be assigned the value of the object literal { b : 1 }
.
这种语法方法通常用于定义默认值。
This method of syntax is usually used to define default values.
例如:
function say_hello( name ){
var the_name = name || 'Dude';
alert( "Hello, " + the_name );
}
say_hello( "Lix" ); // OUTPUTS: Hello, Lix
say_hello(); // OUTPUTS: Hello, Dude
如果参数 name
尚未传递给该函数,将使用默认名称 Dude
。
If the argument name
has not been passed to the function, the default name Dude
will be used.
这篇关于'var a = a ||的目的是什么? {b:1}'语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!