简体   繁体   English

Javascript初学者:逻辑或空括号

[英]Javascript beginner: logical or and empty brackets

Here's the Javascript code: 这是Javascript代码:

var _a = _a || [];

Why it uses "||" 为什么使用“ ||” (logical OR) and "[]" (an empty array) together? (逻辑或)和“ []”(空数组)在一起?

The expression _a || [] 表达式_a || [] _a || [] will return _a if it is "truthy", otherwise [] (it is short circuiting, so it only evaluates until one of the operands is 'true' or they have all been evaluated). 如果_a || []是“真”,则[] _a _a || []将返回_a ,否则返回[] (这是短路的,因此它仅求值,直到其中一个操作数为'true'或已对它们全部求值)。

This is essentially checking for null. 这实际上是检查null。 If _a is null or undefined (or false, but that is not likely in this scenario) then it is initialized to an empty array. 如果_a为null或未定义(或为false,但在这种情况下不太可能),则将其初始化为空数组。

This makes a default state\\value. 这将成为默认状态\\值。 If there is not an _a in the current scope or it is no true or value of any type, it will be created as an empty array. 如果当前范围中没有_a或它不是true或任何类型的值,它将被创建为一个空数组。 If it exists, it will be reassigned to itself, which is not a very good practice. 如果存在,则将其重新分配给自己,这不是一个很好的做法。 It is useful in 2 cases: 在2种情况下很有用:

  1. inside a method ( function ) - another function may return an array or null (for example). 在方法(函数)内部-另一个函数可能返回数组或null(例如)。 If in the method you implicitly needs an array, you assure that _a is an array: 如果在该方法中隐式需要一个数组,请确保_a是一个数组:

    var _a = _a || [];

  2. passed as parameter - if you need to pass array as an argument. 作为参数传递-如果需要将数组作为参数传递。 If the argument is null and inside the method you implicitly need an array (this is assigning a default parameter), but it should not override the parameter. 如果参数为null且在方法内部,则隐式需要一个数组(这是分配默认参数),但不应覆盖该参数。 It must be assigned to a new variable (I think this is the case because of the underscore): 必须将其分配给新变量(由于下划线,我认为是这种情况):

function doSomething ( a, b, c ) 
{
   ...
   var _a = a || [];
   ...
}

如果已定义_a则使用其值,否则初始化一个空数组

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM