javascript:这是一个条件分配吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6167883/
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 19:43:44  来源:igfitidea点击:

javascript: is this a conditional assignment?

javascript

提问by mikkelbreum

From the google analytics tracking code:

从谷歌分析跟踪代码:

var _gaq = _gaq || [];

how does this work?

这是如何运作的?

Is it a conditional variable value assignment? Is it the same as saying:

是条件变量赋值吗?是不是和说一样:

if( !(_gaq) ) {_gaq = []; }

?

?

采纳答案by Quentin

The or operator (||) will return the left hand side if it is a true value, otherwise it will return the right hand side.

如果 or 运算符 ( ||) 为真值,则将返回左侧,否则将返回右侧。

It is very similar to your second example, but since it makes use of the varkeyword, it also establishes a local scope for the variable.

它与您的第二个示例非常相似,但由于它使用了var关键字,因此它还为变量建立了一个局部作用域。

回答by SLaks

Yes, it is.

是的。

The ||operator evaluates to its leftmost "truthy" operand.
If _gaqis "falsy" (such as null, undefined, or 0), it will evaluate to the right side ([]).

||运算符计算它的最左边的“truthy”操作数。
如果_gaq是“falsy”(例如null, undefined, 或0),它将评估到右侧([])。

回答by Brett Zamir

It's the same as saying:

这就像说:

if( !(_gaq) ) {var _gaq = [];}

(This can be done since the var is hoisted above the conditional check, thereby avoiding a 'not defined' error, and it will also cause _gaq to be automatically treated as local in scope.)

(这是可以做到的,因为 var 被提升到条件检查之上,从而避免了“未定义”错误,并且还会导致 _gaq 在范围内被自动视为本地。)

回答by Pointy

Actually it's notthe same as saying:

其实这并不等于说:

if (!_gaq) _gaq = [];

at least not necessarily. Consider this:

至少不一定。考虑一下:

function outer() {
  var _gaq = null;
  function inner() {
    var _gaq = _gaq || [];
    // ...
  }

  inner();
  _gaq = 1;
  inner();
}

When there's a "_gaq" (I hate typing that, by the way) in an outer lexical scope, what you end up with is a newvariable in the inner scope. The "if" statement differs in that very important way — there would only be one "_gaq" in that case.

当外部词法作用域中有一个“_gaq”(顺便说一句,我讨厌输入它)时,您最终得到的是内部作用域中的一个变量。“if”语句在这一非常重要的方面有所不同——在这种情况下只有一个“_gaq”。