构造x = x || y是什么意思?

时间:2022-06-17 22:26:38

I am debugging some JavaScript, and can't explain what this || does?

我正在调试一些JavaScript,无法解释||做了什么?

function (title, msg) {
  var title = title || 'Error';
  var msg   = msg || 'Error on Request';
}

Can someone give me an hint, why this guy is using var title = title || 'ERROR'? I sometimes see it without a var declaration as well.

有人能给我一个提示吗,为什么这个家伙使用var title =标题|| 'ERROR'?我有时也会看到它没有var声明。

11 个解决方案

#1


157  

It means the title argument is optional. So if you call the method with no arguments it will use a default value of "Error".

这意味着标题参数是可选的。因此,如果您调用了没有参数的方法,它将使用默认值“Error”。

It's shorthand for writing:

这是缩写写:

if (!title) {
  title = "Error";
}

This kind of shorthand trick with boolean expressions is common in Perl too. With the expression:

这种布尔表达式的简写技巧在Perl中也很常见。表达式:

a OR b

it evaluates to true if either a or b is true. So if a is true you don't need to check b at all. This is called short-circuit boolean evaluation so:

如果a或b为真,则为真。如果a是真的,你根本不需要检查b。这就是所谓的短路布尔评价:

var title = title || "Error";

basically checks if title evaluates to false. If it does, it "returns" "Error", otherwise it returns title.

基本上检查title是否为false。如果是,则返回“Error”,否则返回标题。

#2


94  

What is the double pipe operator (||)?

The double pipe operator (||) is the logical OR operator . In most languages it works the following way:

双管道操作符(||)是逻辑或操作符。在大多数语言中,它的工作方式如下:

  • If the first value is false, it checks the second value. If it's true, it returns true and if it's false, it returns false.
  • 如果第一个值为false,则检查第二个值。如果它为真,它返回true,如果它是假的,它返回false。
  • If the first value is true, it always returns true, no matter what the second value is.
  • 如果第一个值是true,那么它总是返回true,无论第二个值是什么。

So basically it works like this function:

基本上它是这样运作的:

function or(x, y) {
  if (x) {
    return true;
  } else if (y) {
    return true;
  } else {
    return false;
  }
}

If you still don't understand, look at this table:

如果你还是不明白,看看这张桌子:

      | true   false  
------+---------------
true  | true   true   
false | true   false  

In other words, it's only false when both values are false.

换句话说,只有当两个值都为假时,它才为假。

How is it different in JavaScript?

JavaScript is a bit different, because it's a loosely typed language. In this case it means that you can use || operator with values that are not booleans. Though it makes no sense, you can use this operator with for example a function and an object:

JavaScript有点不同,因为它是一种松散类型的语言。在这种情况下,这意味着您可以使用||操作符,其值不是布尔值。虽然没有任何意义,但是可以使用这个操作符,例如一个函数和一个对象:

(function(){}) || {}

What happens there?

If values are not boolean, JavaScript makes implicit conversation to boolean. It means that if the value is falsey (e.g. 0, "", null, undefined (see also All falsey values in JavaScript)), it will be treated as false; otherwise it's treated as true.

如果值不是布尔值,则JavaScript会使隐式对话变为布尔值。它意味着如果值是falsey(例如,0,“,null,未定义(参见JavaScript中的所有falsey值)),那么它将被视为false;否则它就被当作是真的。

So the above example should give true, because empty function is truthy. Well, it doesn't. It returns the empty function. That's because JavaScript's || operator doesn't work as I wrote at the beginning. It works the following way:

所以上面的例子应该是正确的,因为虚函数是真实的。好吧,它不会。它返回空函数。这是因为JavaScript的||运算符不像我在开始时写的那样。它的工作方式如下:

  • If the first value is falsey, it returns the second value.
  • 如果第一个值是falsey,则返回第二个值。
  • If the first value is truthy, it returns the first value.
  • 如果第一个值是truthy,则返回第一个值。

Surprised? Actually, it's "compatible" with the traditional || operator. It could be written as following function:

惊讶吗?实际上,它与传统||操作符“兼容”。它可以写成以下函数:

function or(x, y) {
  if (x) {
    return x;
  } else {
    return y;
  }
}

If you pass a truthy value as x, it returns x, that is, a truthy value. So if you use it later in if clause:

如果你传递一个truthy的值作为x,它返回x,也就是说,一个truthy的值。如果你以后用if从句:

(function(x, y) {
  var eitherXorY = x || y;
  if (eitherXorY) {
    console.log("Either x or y is truthy.");
  } else {
    console.log("Neither x nor y is truthy");
  }
}(true/*, undefined*/));

you get "Either x or y is truthy.".

你得到“要么x要么y是真的”。

If x was falsey, eitherXorY would be y. In this case you would get the "Either x or y is truthy." if y was truthy; otherwise you'd get "Neither x nor y is truthy".

如果x是falsey, eitherXorY是y,在这种情况下,你会得到“x或者y是truthy”,如果y是truthy;否则你会得到“x和y都不真实”。

The actual question

Now, when you know how || operator works, you can probably make out by yourself what does x = x || y mean. If x is truthy, x is assigned to x, so actually nothing happens; otherwise y is assigned to x. It is commonly used to define default parameters in functions. However, it is often considered a bad programming practice, because it prevents you from passing a falsey value (which is not necessarily undefined or null) as a parameter. Consider following example:

现在,当你知道||运算符是如何工作的,你可以自己弄清楚x = x || y是什么意思。如果x是真实的,x被分配到x,所以实际上什么也没有发生;否则y被分配给x,通常用来定义函数中的默认参数。然而,它通常被认为是一种糟糕的编程实践,因为它阻止您传递一个falsey值(它不一定是未定义的或null)作为参数。考虑下面的例子:

function badFunction(/* boolean */flagA) {
  flagA = flagA || true;
  console.log("flagA is set to " + (flagA ? "true" : "false"));
}

It looks valid at the first sight. However, what would happen if you passed false as flagA parameter (since it's boolean, i.e. can be true or false)? It would become true. In this example, there is no way to set flagA to false.

乍一看,它是有效的。但是,如果您传递false作为flagA参数会发生什么(因为它是布尔型的,即可能是真或假)?它将成为事实。在本例中,没有办法将flagA设置为false。

It would be a better idea to explicitly check whether flagA is undefined, like that:

明确地检查flagA是否没有定义是一个更好的主意,比如:

function goodFunction(/* boolean */flagA) {
  flagA = typeof flagA !== "undefined" ? flagA : true;
  console.log("flagA is set to " + (flagA ? "true" : "false"));
}

Though it's longer, it always works and it's easier to understand.

虽然时间比较长,但它总是有效的,而且更容易理解。


You can also use the ES6 syntax for default function parameters, but note that it doesn't work in older browsers (like IE). If you want to support these browsers, you should transpile your code with Babel.

您还可以使用ES6语法作为默认的函数参数,但是注意它在旧的浏览器中不起作用(比如IE)。如果您想要支持这些浏览器,您应该将您的代码与Babel进行转换。

See also Logical Operators on MDN.

请参阅MDN上的逻辑运算符。

#3


23  

If title is not set, use 'ERROR' as default value.

如果标题没有设置,则使用“ERROR”作为默认值。

More generic:

更通用的:

var foobar = foo || default;

Reads: Set foobar to foo or default. You could even chain this up many times:

读取:将foobar设置为foo或default。你甚至可以把它连起来很多次:

var foobar = foo || bar || something || 42;

#4


13  

Explaining this a little more...

再解释一下……

The || operator is the logical-or operator. The result is true if the first part is true and it is true if the second part is true and it is true if both parts are true. For clarity, here it is in a table:

||操作符是逻辑或操作符。如果第一部分为真,则结果为真,如果第二部分为真,则为真,如果这两个部分为真,则为真。为了清晰起见,这里是一个表格:

 X | Y | X || Y 
---+---+--------
 F | F |   F    
---+---+--------
 F | T |   T    
---+---+--------
 T | F |   T    
---+---+--------
 T | T |   T    
---+---+--------

Now notice something here? If X is true, the result is always true. So if we know that X is true we don't have to check Y at all. Many languages thus implement "short circuit" evaluators for logical-or (and logical-and coming from the other direction). They check the first element and if that's true they don't bother checking the second at all. The result (in logical terms) is the same, but in terms of execution there's potentially a huge difference if the second element is expensive to calculate.

现在注意到一些东西吗?如果X是真的,结果总是正确的。如果我们知道X是真的,我们就不需要检查Y了。因此,许多语言都为逻辑或逻辑(以及逻辑-和从另一个方向来)实现了“短路”评估器。他们检查第一个元素,如果这是真的,他们就不会去检查第二个元素。结果(在逻辑上)是相同的,但是在执行方面,如果第二个元素的计算代价很高,那么可能会产生巨大的差异。

So what does this have to do with your example?

这和你的例子有什么关系呢?

var title   = title || 'Error';

Let's look at that. The title element is passed in to your function. In JavaScript if you don't pass in a parameter, it defaults to a null value. Also in JavaScript if your variable is a null value it is considered to be false by the logical operators. So if this function is called with a title given, it is a non-false value and thus assigned to the local variable. If, however, it is not given a value, it is a null value and thus false. The logical-or operator then evaluates the second expression and returns 'Error' instead. So now the local variable is given the value 'Error'.

让我们来看看。title元素被传递到您的函数中。在JavaScript中,如果不传递参数,则默认为空值。在JavaScript中,如果变量是空值,逻辑运算符认为它是假的。因此,如果这个函数被称为给定的标题,它是一个非虚值,因此被赋值给局部变量。但是,如果没有给定值,则为空值,因此为false。然后,logicor运算符计算第二个表达式并返回“Error”。现在,本地变量被赋予了值'Error'。

This works because of the implementation of logical expressions in JavaScript. It doesn't return a proper boolean value (true or false) but instead returns the value it was given under some rules as to what's considered equivalent to true and what's considered equivalent to false. Look up your JavaScript reference to learn what JavaScript considers to be true or false in boolean contexts.

这是因为JavaScript中的逻辑表达式的实现。它不返回一个正确的布尔值(true或false),而是返回在某些规则下给出的值,这些规则被认为是等价的,以及被认为等同于false的值。查找您的JavaScript引用,以了解在布尔上下文中JavaScript认为是真还是假。

#5


7  

Double pipe stands for logical "OR". This is not really the case when the "parameter not set", since strictly in the javascript if you have code like this:

双管代表逻辑“或”。当“参数未设置”时,这不是真正的情况,因为在javascript中,如果您有这样的代码:

function foo(par) {
}

Then calls

然后调用

foo()
foo("")
foo(null)
foo(undefined)
foo(0)

are not equivalent.

并不是等价的。

Double pipe (||) will cast the first argument to boolean and if resulting boolean is true - do the assignment otherwise it will assign the right part.

双管(||)将会将第一个参数转换为布尔值,如果结果布尔值为真,则执行赋值,否则将分配正确的部分。

This matters if you check for unset parameter.

这很重要,如果您检查unset参数。

Let's say, we have a function setSalary that has one optional parameter. If user does not supply the parameter then the default value of 10 should be used.

比方说,我们有一个函数setSalary,它有一个可选参数。如果用户不提供参数,则应该使用默认值10。

if you do the check like this:

如果你做这样的检查:

function setSalary(dollars) {
    salary = dollars || 10
}

This will give unexpected result on call like

这将给你的电话带来意想不到的结果。

setSalary(0) 

It will still set the 10 following the flow described above.

它仍将按照上面描述的流程设置10。

#6


6  

Basically it checks if the value before the || evaluates to true, if yes, it takes this value, if not, it takes the value after the ||.

基本上它会检查||之前的值是否为true,如果是,它取这个值,如果不是,它取||之后的值。

Values for which it will take the value after the || (as far as i remember):

||后的值(我记得):

  • undefined
  • 未定义的
  • false
  • 0
  • 0
  • '' (Null or Null string)
  • (Null或空字符串)

#7


3  

double pipe operator

双管操作符

is this example usefull?

这是例子有用吗?

var section = document.getElementById('special');
if(!section){
     section = document.getElementById('main');
}

can also be

也可以

var section = document.getElementById('special') || document.getElementById('main');

#8


2  

Whilst Cletus' answer is correct, I feel more detail should be added in regards to "evaluates to false" in JavaScript.

虽然Cletus的回答是正确的,但我觉得在JavaScript中应该添加更多的细节来“评估为false”。

var title = title || 'Error';
var msg   = msg || 'Error on Request';

Is not just checking if title/msg has been provided, but also if either of them are falsy. i.e. one of the following:

不只是检查是否提供了标题/msg,而且如果其中任何一个都是假的。其中一项:

  • false.
  • 假的。
  • 0 (zero)
  • 0(零)
  • "" (empty string)
  • " "(空字符串)
  • null.
  • null。
  • undefined.
  • 未定义的。
  • NaN (a special Number value meaning Not-a-Number!)
  • NaN(一个特殊的数值,意思不是数字!)

So in the line

所以在这条线

var title = title || 'Error';

If title is truthy (i.e., not falsy, so title = "titleMessage" etc.) then the Boolean OR (||) operator has found one 'true' value, which means it evaluates to true, so it short-circuits and returns the true value (title).

如果标题是真实的(即:然后,布尔或(||)运算符找到了一个“true”值,这意味着它的值为true,因此它会短路并返回true值(title)。

If title is falsy (i.e. one of the list above), then the Boolean OR (||) operator has found a 'false' value, and now needs to evaluate the other part of the operator, 'Error', which evaluates to true, and is hence returned.

如果标题是falsy(即上面的列表中的一个),那么布尔或(||)运算符就会发现一个“false”值,现在需要对运算符的另一部分进行评估,“Error”,它计算为true,因此返回。

It would also seem (after some quick firebug console experimentation) if both sides of the operator evaluate to false, it returns the second 'falsy' operator.

它也会看起来(在一些快速的firebug控制台实验之后),如果操作员的两边都评估为false,它将返回第二个“falsy”操作符。

i.e.

即。

return ("" || undefined)

returns undefined, this is probably to allow you to use the behavior asked about in this question when trying to default title/message to "". i.e. after running

返回未定义的结果,这可能允许您在尝试默认标题/消息时使用在这个问题中被问到的行为。即在运行

var foo = undefined
foo = foo || ""

foo would be set to ""

foo将被设置为"

#9


2  

Quote: "What does the construct x = x || y mean?"

"构造x = x || y是什么意思?"

Assigning a default value.

分配一个默认值。

This means providing a default value of y to x, in case x is still waiting for its value but hasn't received it yet or was deliberately omitted in order to fall back to a default.

这意味着向x提供y的默认值,以防x仍在等待它的值,但是还没有收到它,或者被故意省略掉,以回到默认值。

#10


1  

To add some explanation to all said before me, I should give you some examples to understand logical concepts.

为了给所有的人增加一些解释,我应该给你一些例子来理解逻辑概念。

var name = false || "Mohsen"; # name equals to Mohsen
var family = true || "Alizadeh" # family equals to true

It means if the left side evaluated as a true statement it will be finished and the left side will be returned and assigned to the variable. in other cases the right side will be returned and assigned.

它的意思是,如果左侧被评估为一个真实的语句,它将被完成,而左边将被返回并分配给变量。在其他情况下,右侧将被返回并分配。

And operator have the opposite structure like below.

而操作员的结构与下面的相反。

var name = false && "Mohsen" # name equals to false
var family = true && "Alizadeh" # family equals to Alizadeh

#11


-4  

And I have to add one more thing: This bit of shorthand is an abomination. It misuses an accidental interpreter optimization (not bothering with the second operation if the first is truthy) to control an assignment. That use has nothing to do with the purpose of the operator. I do not believe it should ever be used.

我还得再加一件事:这种速记法是令人厌恶的。它错误地使用了一个偶然的解释器优化(如果第一个操作是truthy的),它会对一个任务进行控制。这种用法与操作者的目的无关。我不认为它应该被使用。

I prefer the ternary operator for initialization, eg,

我喜欢初始化的三元运算符,例如,

var title = title?title:'Error';

This uses a one-line conditional operation for its correct purpose. It still plays unsightly games with truthiness but, that's Javascript for you.

它使用一行条件操作来实现其正确的目的。它仍然会用truthiness来播放难看的游戏,但这就是Javascript。

#1


157  

It means the title argument is optional. So if you call the method with no arguments it will use a default value of "Error".

这意味着标题参数是可选的。因此,如果您调用了没有参数的方法,它将使用默认值“Error”。

It's shorthand for writing:

这是缩写写:

if (!title) {
  title = "Error";
}

This kind of shorthand trick with boolean expressions is common in Perl too. With the expression:

这种布尔表达式的简写技巧在Perl中也很常见。表达式:

a OR b

it evaluates to true if either a or b is true. So if a is true you don't need to check b at all. This is called short-circuit boolean evaluation so:

如果a或b为真,则为真。如果a是真的,你根本不需要检查b。这就是所谓的短路布尔评价:

var title = title || "Error";

basically checks if title evaluates to false. If it does, it "returns" "Error", otherwise it returns title.

基本上检查title是否为false。如果是,则返回“Error”,否则返回标题。

#2


94  

What is the double pipe operator (||)?

The double pipe operator (||) is the logical OR operator . In most languages it works the following way:

双管道操作符(||)是逻辑或操作符。在大多数语言中,它的工作方式如下:

  • If the first value is false, it checks the second value. If it's true, it returns true and if it's false, it returns false.
  • 如果第一个值为false,则检查第二个值。如果它为真,它返回true,如果它是假的,它返回false。
  • If the first value is true, it always returns true, no matter what the second value is.
  • 如果第一个值是true,那么它总是返回true,无论第二个值是什么。

So basically it works like this function:

基本上它是这样运作的:

function or(x, y) {
  if (x) {
    return true;
  } else if (y) {
    return true;
  } else {
    return false;
  }
}

If you still don't understand, look at this table:

如果你还是不明白,看看这张桌子:

      | true   false  
------+---------------
true  | true   true   
false | true   false  

In other words, it's only false when both values are false.

换句话说,只有当两个值都为假时,它才为假。

How is it different in JavaScript?

JavaScript is a bit different, because it's a loosely typed language. In this case it means that you can use || operator with values that are not booleans. Though it makes no sense, you can use this operator with for example a function and an object:

JavaScript有点不同,因为它是一种松散类型的语言。在这种情况下,这意味着您可以使用||操作符,其值不是布尔值。虽然没有任何意义,但是可以使用这个操作符,例如一个函数和一个对象:

(function(){}) || {}

What happens there?

If values are not boolean, JavaScript makes implicit conversation to boolean. It means that if the value is falsey (e.g. 0, "", null, undefined (see also All falsey values in JavaScript)), it will be treated as false; otherwise it's treated as true.

如果值不是布尔值,则JavaScript会使隐式对话变为布尔值。它意味着如果值是falsey(例如,0,“,null,未定义(参见JavaScript中的所有falsey值)),那么它将被视为false;否则它就被当作是真的。

So the above example should give true, because empty function is truthy. Well, it doesn't. It returns the empty function. That's because JavaScript's || operator doesn't work as I wrote at the beginning. It works the following way:

所以上面的例子应该是正确的,因为虚函数是真实的。好吧,它不会。它返回空函数。这是因为JavaScript的||运算符不像我在开始时写的那样。它的工作方式如下:

  • If the first value is falsey, it returns the second value.
  • 如果第一个值是falsey,则返回第二个值。
  • If the first value is truthy, it returns the first value.
  • 如果第一个值是truthy,则返回第一个值。

Surprised? Actually, it's "compatible" with the traditional || operator. It could be written as following function:

惊讶吗?实际上,它与传统||操作符“兼容”。它可以写成以下函数:

function or(x, y) {
  if (x) {
    return x;
  } else {
    return y;
  }
}

If you pass a truthy value as x, it returns x, that is, a truthy value. So if you use it later in if clause:

如果你传递一个truthy的值作为x,它返回x,也就是说,一个truthy的值。如果你以后用if从句:

(function(x, y) {
  var eitherXorY = x || y;
  if (eitherXorY) {
    console.log("Either x or y is truthy.");
  } else {
    console.log("Neither x nor y is truthy");
  }
}(true/*, undefined*/));

you get "Either x or y is truthy.".

你得到“要么x要么y是真的”。

If x was falsey, eitherXorY would be y. In this case you would get the "Either x or y is truthy." if y was truthy; otherwise you'd get "Neither x nor y is truthy".

如果x是falsey, eitherXorY是y,在这种情况下,你会得到“x或者y是truthy”,如果y是truthy;否则你会得到“x和y都不真实”。

The actual question

Now, when you know how || operator works, you can probably make out by yourself what does x = x || y mean. If x is truthy, x is assigned to x, so actually nothing happens; otherwise y is assigned to x. It is commonly used to define default parameters in functions. However, it is often considered a bad programming practice, because it prevents you from passing a falsey value (which is not necessarily undefined or null) as a parameter. Consider following example:

现在,当你知道||运算符是如何工作的,你可以自己弄清楚x = x || y是什么意思。如果x是真实的,x被分配到x,所以实际上什么也没有发生;否则y被分配给x,通常用来定义函数中的默认参数。然而,它通常被认为是一种糟糕的编程实践,因为它阻止您传递一个falsey值(它不一定是未定义的或null)作为参数。考虑下面的例子:

function badFunction(/* boolean */flagA) {
  flagA = flagA || true;
  console.log("flagA is set to " + (flagA ? "true" : "false"));
}

It looks valid at the first sight. However, what would happen if you passed false as flagA parameter (since it's boolean, i.e. can be true or false)? It would become true. In this example, there is no way to set flagA to false.

乍一看,它是有效的。但是,如果您传递false作为flagA参数会发生什么(因为它是布尔型的,即可能是真或假)?它将成为事实。在本例中,没有办法将flagA设置为false。

It would be a better idea to explicitly check whether flagA is undefined, like that:

明确地检查flagA是否没有定义是一个更好的主意,比如:

function goodFunction(/* boolean */flagA) {
  flagA = typeof flagA !== "undefined" ? flagA : true;
  console.log("flagA is set to " + (flagA ? "true" : "false"));
}

Though it's longer, it always works and it's easier to understand.

虽然时间比较长,但它总是有效的,而且更容易理解。


You can also use the ES6 syntax for default function parameters, but note that it doesn't work in older browsers (like IE). If you want to support these browsers, you should transpile your code with Babel.

您还可以使用ES6语法作为默认的函数参数,但是注意它在旧的浏览器中不起作用(比如IE)。如果您想要支持这些浏览器,您应该将您的代码与Babel进行转换。

See also Logical Operators on MDN.

请参阅MDN上的逻辑运算符。

#3


23  

If title is not set, use 'ERROR' as default value.

如果标题没有设置,则使用“ERROR”作为默认值。

More generic:

更通用的:

var foobar = foo || default;

Reads: Set foobar to foo or default. You could even chain this up many times:

读取:将foobar设置为foo或default。你甚至可以把它连起来很多次:

var foobar = foo || bar || something || 42;

#4


13  

Explaining this a little more...

再解释一下……

The || operator is the logical-or operator. The result is true if the first part is true and it is true if the second part is true and it is true if both parts are true. For clarity, here it is in a table:

||操作符是逻辑或操作符。如果第一部分为真,则结果为真,如果第二部分为真,则为真,如果这两个部分为真,则为真。为了清晰起见,这里是一个表格:

 X | Y | X || Y 
---+---+--------
 F | F |   F    
---+---+--------
 F | T |   T    
---+---+--------
 T | F |   T    
---+---+--------
 T | T |   T    
---+---+--------

Now notice something here? If X is true, the result is always true. So if we know that X is true we don't have to check Y at all. Many languages thus implement "short circuit" evaluators for logical-or (and logical-and coming from the other direction). They check the first element and if that's true they don't bother checking the second at all. The result (in logical terms) is the same, but in terms of execution there's potentially a huge difference if the second element is expensive to calculate.

现在注意到一些东西吗?如果X是真的,结果总是正确的。如果我们知道X是真的,我们就不需要检查Y了。因此,许多语言都为逻辑或逻辑(以及逻辑-和从另一个方向来)实现了“短路”评估器。他们检查第一个元素,如果这是真的,他们就不会去检查第二个元素。结果(在逻辑上)是相同的,但是在执行方面,如果第二个元素的计算代价很高,那么可能会产生巨大的差异。

So what does this have to do with your example?

这和你的例子有什么关系呢?

var title   = title || 'Error';

Let's look at that. The title element is passed in to your function. In JavaScript if you don't pass in a parameter, it defaults to a null value. Also in JavaScript if your variable is a null value it is considered to be false by the logical operators. So if this function is called with a title given, it is a non-false value and thus assigned to the local variable. If, however, it is not given a value, it is a null value and thus false. The logical-or operator then evaluates the second expression and returns 'Error' instead. So now the local variable is given the value 'Error'.

让我们来看看。title元素被传递到您的函数中。在JavaScript中,如果不传递参数,则默认为空值。在JavaScript中,如果变量是空值,逻辑运算符认为它是假的。因此,如果这个函数被称为给定的标题,它是一个非虚值,因此被赋值给局部变量。但是,如果没有给定值,则为空值,因此为false。然后,logicor运算符计算第二个表达式并返回“Error”。现在,本地变量被赋予了值'Error'。

This works because of the implementation of logical expressions in JavaScript. It doesn't return a proper boolean value (true or false) but instead returns the value it was given under some rules as to what's considered equivalent to true and what's considered equivalent to false. Look up your JavaScript reference to learn what JavaScript considers to be true or false in boolean contexts.

这是因为JavaScript中的逻辑表达式的实现。它不返回一个正确的布尔值(true或false),而是返回在某些规则下给出的值,这些规则被认为是等价的,以及被认为等同于false的值。查找您的JavaScript引用,以了解在布尔上下文中JavaScript认为是真还是假。

#5


7  

Double pipe stands for logical "OR". This is not really the case when the "parameter not set", since strictly in the javascript if you have code like this:

双管代表逻辑“或”。当“参数未设置”时,这不是真正的情况,因为在javascript中,如果您有这样的代码:

function foo(par) {
}

Then calls

然后调用

foo()
foo("")
foo(null)
foo(undefined)
foo(0)

are not equivalent.

并不是等价的。

Double pipe (||) will cast the first argument to boolean and if resulting boolean is true - do the assignment otherwise it will assign the right part.

双管(||)将会将第一个参数转换为布尔值,如果结果布尔值为真,则执行赋值,否则将分配正确的部分。

This matters if you check for unset parameter.

这很重要,如果您检查unset参数。

Let's say, we have a function setSalary that has one optional parameter. If user does not supply the parameter then the default value of 10 should be used.

比方说,我们有一个函数setSalary,它有一个可选参数。如果用户不提供参数,则应该使用默认值10。

if you do the check like this:

如果你做这样的检查:

function setSalary(dollars) {
    salary = dollars || 10
}

This will give unexpected result on call like

这将给你的电话带来意想不到的结果。

setSalary(0) 

It will still set the 10 following the flow described above.

它仍将按照上面描述的流程设置10。

#6


6  

Basically it checks if the value before the || evaluates to true, if yes, it takes this value, if not, it takes the value after the ||.

基本上它会检查||之前的值是否为true,如果是,它取这个值,如果不是,它取||之后的值。

Values for which it will take the value after the || (as far as i remember):

||后的值(我记得):

  • undefined
  • 未定义的
  • false
  • 0
  • 0
  • '' (Null or Null string)
  • (Null或空字符串)

#7


3  

double pipe operator

双管操作符

is this example usefull?

这是例子有用吗?

var section = document.getElementById('special');
if(!section){
     section = document.getElementById('main');
}

can also be

也可以

var section = document.getElementById('special') || document.getElementById('main');

#8


2  

Whilst Cletus' answer is correct, I feel more detail should be added in regards to "evaluates to false" in JavaScript.

虽然Cletus的回答是正确的,但我觉得在JavaScript中应该添加更多的细节来“评估为false”。

var title = title || 'Error';
var msg   = msg || 'Error on Request';

Is not just checking if title/msg has been provided, but also if either of them are falsy. i.e. one of the following:

不只是检查是否提供了标题/msg,而且如果其中任何一个都是假的。其中一项:

  • false.
  • 假的。
  • 0 (zero)
  • 0(零)
  • "" (empty string)
  • " "(空字符串)
  • null.
  • null。
  • undefined.
  • 未定义的。
  • NaN (a special Number value meaning Not-a-Number!)
  • NaN(一个特殊的数值,意思不是数字!)

So in the line

所以在这条线

var title = title || 'Error';

If title is truthy (i.e., not falsy, so title = "titleMessage" etc.) then the Boolean OR (||) operator has found one 'true' value, which means it evaluates to true, so it short-circuits and returns the true value (title).

如果标题是真实的(即:然后,布尔或(||)运算符找到了一个“true”值,这意味着它的值为true,因此它会短路并返回true值(title)。

If title is falsy (i.e. one of the list above), then the Boolean OR (||) operator has found a 'false' value, and now needs to evaluate the other part of the operator, 'Error', which evaluates to true, and is hence returned.

如果标题是falsy(即上面的列表中的一个),那么布尔或(||)运算符就会发现一个“false”值,现在需要对运算符的另一部分进行评估,“Error”,它计算为true,因此返回。

It would also seem (after some quick firebug console experimentation) if both sides of the operator evaluate to false, it returns the second 'falsy' operator.

它也会看起来(在一些快速的firebug控制台实验之后),如果操作员的两边都评估为false,它将返回第二个“falsy”操作符。

i.e.

即。

return ("" || undefined)

returns undefined, this is probably to allow you to use the behavior asked about in this question when trying to default title/message to "". i.e. after running

返回未定义的结果,这可能允许您在尝试默认标题/消息时使用在这个问题中被问到的行为。即在运行

var foo = undefined
foo = foo || ""

foo would be set to ""

foo将被设置为"

#9


2  

Quote: "What does the construct x = x || y mean?"

"构造x = x || y是什么意思?"

Assigning a default value.

分配一个默认值。

This means providing a default value of y to x, in case x is still waiting for its value but hasn't received it yet or was deliberately omitted in order to fall back to a default.

这意味着向x提供y的默认值,以防x仍在等待它的值,但是还没有收到它,或者被故意省略掉,以回到默认值。

#10


1  

To add some explanation to all said before me, I should give you some examples to understand logical concepts.

为了给所有的人增加一些解释,我应该给你一些例子来理解逻辑概念。

var name = false || "Mohsen"; # name equals to Mohsen
var family = true || "Alizadeh" # family equals to true

It means if the left side evaluated as a true statement it will be finished and the left side will be returned and assigned to the variable. in other cases the right side will be returned and assigned.

它的意思是,如果左侧被评估为一个真实的语句,它将被完成,而左边将被返回并分配给变量。在其他情况下,右侧将被返回并分配。

And operator have the opposite structure like below.

而操作员的结构与下面的相反。

var name = false && "Mohsen" # name equals to false
var family = true && "Alizadeh" # family equals to Alizadeh

#11


-4  

And I have to add one more thing: This bit of shorthand is an abomination. It misuses an accidental interpreter optimization (not bothering with the second operation if the first is truthy) to control an assignment. That use has nothing to do with the purpose of the operator. I do not believe it should ever be used.

我还得再加一件事:这种速记法是令人厌恶的。它错误地使用了一个偶然的解释器优化(如果第一个操作是truthy的),它会对一个任务进行控制。这种用法与操作者的目的无关。我不认为它应该被使用。

I prefer the ternary operator for initialization, eg,

我喜欢初始化的三元运算符,例如,

var title = title?title:'Error';

This uses a one-line conditional operation for its correct purpose. It still plays unsightly games with truthiness but, that's Javascript for you.

它使用一行条件操作来实现其正确的目的。它仍然会用truthiness来播放难看的游戏,但这就是Javascript。