JavaScript OR (||) 变量赋值说明
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2100758/
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
JavaScript OR (||) variable assignment explanation
提问by chattsm
Given this snippet of JavaScript...
鉴于此 JavaScript 片段...
var a;
var b = null;
var c = undefined;
var d = 4;
var e = 'five';
var f = a || b || c || d || e;
alert(f); // 4
Can someone please explain to me what this technique is called (my best guess is in the title of this question!)? And how/why it works exactly?
有人可以向我解释这种技术的名称吗(我最好的猜测是在这个问题的标题中!)?以及它如何/为什么完全起作用?
My understanding is that variable fwill be assigned the nearest value (from left to right) of the first variable that has a value that isn't either null or undefined, but I've not managed to find much reference material about this technique and have seen it used a lot.
我的理解是,变量f将被分配到第一个变量的最近值(从左到右),该变量的值既不是 null 也不是未定义,但我没有找到很多关于这种技术的参考资料,并且有看到它用了很多。
Also, is this technique specific to JavaScript? I know doing something similar in PHP would result in fhaving a true boolean value, rather than the value of ditself.
另外,这种技术是否特定于 JavaScript?我知道在 PHP 中做类似的事情会产生f一个真正的布尔值,而不是d它本身的值。
采纳答案by unwind
See short-circuit evaluationfor the explanation. It's a common way of implementing these operators; it is not unique to JavaScript.
有关说明,请参阅短路评估。这是实现这些运算符的常用方法;它不是 JavaScript 独有的。
回答by CMS
This is made to assign a default value, in this case the value of y, if the xvariable is falsy.
这样做是为了分配一个默认值,在这种情况下y,如果x变量为假,则为 的值。
The boolean operators in JavaScript can return an operand, and not always a boolean result as in other languages.
JavaScript 中的布尔运算符可以返回一个操作数,而不是其他语言中的布尔结果。
The Logical OR operator (||) returns the value of its second operand, if the first one is falsy, otherwise the value of the first operand is returned.
||如果第一个操作数为假,则逻辑 OR 运算符 ( ) 返回其第二个操作数的值,否则返回第一个操作数的值。
For example:
例如:
"foo" || "bar"; // returns "foo"
false || "bar"; // returns "bar"
Falsyvalues are those who coerce to falsewhen used in boolean context, and they are 0, null, undefined, an empty string, NaNand of course false.
假值是那些false在布尔上下文中使用时强制的值,它们是0, null, undefined, 一个空字符串,NaN当然还有false.
回答by Anurag
Javacript uses short-circuit evaluationfor logical operators ||and &&. However, it's different to other languages in that it returns the result of the last value that halted the execution, instead of a true, or falsevalue.
Javacript使用短路评价为逻辑运算符||和&&。但是,它与其他语言的不同之处在于它返回停止执行的最后一个值的结果,而不是一个true, 或false值。
The following values are considered falsy in JavaScript.
以下值在 JavaScript 中被认为是假的。
- false
- null
""(empty string)- 0
- Nan
- undefined
- 错误的
- 空值
""(空字符串)- 0
- 南
- 不明确的
Ignoring the operator precedencerules, and keeping things simple, the following examples show which value halted the evaluation, and gets returned as a result.
忽略运算符优先级规则并保持简单,以下示例显示哪个值停止了评估,并作为结果返回。
false || null || "" || 0 || NaN || "Hello" || undefined // "Hello"
The first 5 values upto NaNare falsy so they are all evaluated from left to right, until it meets the first truthy value - "Hello"which makes the entire expression true, so anything further up will not be evaluated, and "Hello"gets returned as a result of the expression. Similarly, in this case:
前 5 个值NaN是假的,所以它们都是从左到右求值的,直到它遇到第一个真值——"Hello"这使得整个表达式为真,所以后面的任何值都不会被求值,并"Hello"作为表达式的结果返回. 同样,在这种情况下:
1 && [] && {} && true && "World" && null && 2010 // null
The first 5 values are all truthy and get evaluated until it meets the first falsy value (null) which makes the expression false, so 2010isn't evaluated anymore, and nullgets returned as a result of the expression.
前 5 个值都是真值并进行求值,直到遇到第一个假值 ( null),这使表达式为假,因此2010不再求值,并null作为表达式的结果返回。
The example you've given is making use of this property of JavaScript to perform an assignment. It can be used anywhere where you need to get the first truthy or falsy value among a set of values. This code below will assign the value "Hello"to bas it makes it easier to assign a default value, instead of doing if-else checks.
你给出的例子是利用 JavaScript 的这个属性来执行赋值。它可以用于需要在一组值中获得第一个真值或假值的任何地方。下面的代码将分配值"Hello",b因为它可以更轻松地分配默认值,而不是进行 if-else 检查。
var a = false;
var b = a || "Hello";
You could call the below example an exploitation of this feature, and I believe it makes code harder to read.
您可以将以下示例称为对该功能的利用,我相信它会使代码更难阅读。
var messages = 0;
var newMessagesText = "You have " + messages + " messages.";
var noNewMessagesText = "Sorry, you have no new messages.";
alert((messages && newMessagesText) || noNewMessagesText);
Inside the alert, we check if messagesis falsy, and if yes, then evaluate and return noNewMessagesText, otherwise evaluate and return newMessagesText. Since it's falsy in this example, we halt at noNewMessagesText and alert "Sorry, you have no new messages.".
在警报内部,我们检查是否messages为假,如果是,则评估并返回noNewMessagesText,否则评估并返回newMessagesText。因为在这个例子中它是假的,我们在 noNewMessagesText 和 alert 处停止"Sorry, you have no new messages."。
回答by Alsciende
Javascript variables are not typed, so f can be assigned an integer value even though it's been assigned through boolean operators.
Javascript 变量没有类型化,因此即使 f 是通过布尔运算符分配的,也可以为其分配整数值。
f is assigned the nearest value that is not equivalent to false. So 0, false, null, undefined, are all passed over:
f 被分配了不等于 false的最接近的值。所以 0、false、null、undefined 都被忽略了:
alert(null || undefined || false || '' || 0 || 4 || 'bar'); // alerts '4'
回答by Marcin
There isn't any magic to it. Boolean expressions like a || b || c || dare lazily evaluated. Interpeter looks for the value of a, it's undefined so it's false so it moves on, then it sees bwhich is null, which still gives false result so it moves on, then it sees c- same story. Finally it sees dand says 'huh, it's not null, so I have my result' and it assigns it to the final variable.
它没有任何魔法。像这样的布尔表达式a || b || c || d被惰性求值。Interpeter 寻找 的值a,它是未定义的,所以它是假的,所以它继续前进,然后它看到b哪个是空的,它仍然给出错误的结果,所以它继续前进,然后它看到c- 同样的故事。最后它看到d并说“嗯,它不是空的,所以我有我的结果”,并将它分配给最终变量。
This trick will work in all dynamic languages that do lazy short-circuit evaluation of boolean expressions. In static languages it won't compile (type error). In languages that are eager in evaluating boolean expressions, it'll return logical value (i.e. true in this case).
这个技巧适用于所有对布尔表达式进行惰性短路评估的动态语言。在静态语言中,它不会编译(类型错误)。在渴望评估布尔表达式的语言中,它将返回逻辑值(即在这种情况下为 true)。
回答by WSimpson
This question has already received several good answers.
这个问题已经得到了几个很好的答案。
In summary, this technique is taking advantage of a feature of how the language is compiled. That is, JavaScript "short-circuits" the evaluation of Boolean operators and will return the value associated with either the first non-false variable value or whatever the last variable contains. See Anurag's explanation of those values that will evaluate to false.
总之,这种技术利用了语言编译方式的一个特性。也就是说,JavaScript“短路”了布尔运算符的计算,并将返回与第一个非假变量值或最后一个变量包含的任何值相关联的值。请参阅 Anurag 对将评估为 false 的那些值的解释。
Using this technique is not good practice for several reasons; however.
出于多种原因,使用这种技术并不是一个好习惯;然而。
- Code Readability: This is using Boolean operators, and if the behavior of how this compiles is not understood, then the expected result would be a Boolean value.
- Stability: This is using a feature of how the language is compiled that is inconsistent across multiple languages, and due to this it is something that could potentially be targeted for change in the future.
Documented Features: There is an existing alternative that meets this need and is consistent across more languages. This would be the ternary operator:
() ? value 1: Value 2.
- 代码可读性:这是使用布尔运算符,如果无法理解其编译方式,则预期结果将是布尔值。
- 稳定性:这是使用语言编译方式在多种语言中不一致的特性,因此它可能成为未来更改的目标。
记录的功能:现有的替代方案可以满足此需求,并且在更多语言中保持一致。这将是三元运算符:
() ? 值 1:值 2。
Using the ternary operator does require a little more typing, but it clearly distinguishes between the Boolean expression being evaluated and the value being assigned. In addition it can be chained, so the types of default assignments being performed above could be recreated.
使用三元运算符确实需要更多的输入,但它清楚地区分了正在计算的布尔表达式和正在分配的值。此外,它可以链接,因此可以重新创建上面执行的默认分配类型。
var a;
var b = null;
var c = undefined;
var d = 4;
var e = 'five';
var f = ( a ) ? a :
( b ) ? b :
( c ) ? c :
( d ) ? d :
e;
alert(f); // 4
回答by Arshid KV
Return output first true value.
返回输出第一个真值。
If all are false return last false value.
如果全部为假,则返回最后一个假值。
Example:-
例子:-
null || undefined || false || 0 || 'apple' // Return apple
回答by Matthew Crumley
It's setting the new variable (z) to either the value of xif it's "truthy" (non-zero, a valid object/array/function/whatever it is) or yotherwise. It's a relatively common way of providing a default value in case xdoesn't exist.
它将新变量 ( z)设置为x“真实”(非零,有效对象/数组/函数/无论它是什么)的值或y其他值。这是在x不存在的情况下提供默认值的一种相对常见的方式。
For example, if you have a function that takes an optional callback parameter, you could provide a default callback that doesn't do anything:
例如,如果您有一个采用可选回调参数的函数,您可以提供一个不执行任何操作的默认回调:
function doSomething(data, callback) {
callback = callback || function() {};
// do stuff with data
callback(); // callback will always exist
}
回答by Vijay
Its called Short circuit operator.
它被称为短路运算符。
Short-circuit evaluation says, the second argument is executed or evaluated only if the first argument does not suffice to determine the value of the expression. when the first argument of the OR (||) function evaluates to true, the overall value must be true.
短路评估表示,仅当第一个参数不足以确定表达式的值时,才会执行或评估第二个参数。当 OR (||) 函数的第一个参数计算结果为真时,整体值必须为真。
It could also be used to set a default value for function argument.`
它还可用于为函数参数设置默认值。`
function theSameOldFoo(name){
name = name || 'Bar' ;
console.log("My best friend's name is " + name);
}
theSameOldFoo(); // My best friend's name is Bar
theSameOldFoo('Bhaskar'); // My best friend's name is Bhaskar`
回答by Andris
It means that if xis set, the value for zwill be x, otherwise if yis set then its value will be set as the z's value.
这意味着如果x设置,则值为zwill x,否则如果y设置则其值将设置为z的值。
it's the same as
它和
if(x)
z = x;
else
z = y;
It's possible because logical operators in JavaScript doesn't return boolean values but the value of the last element needed to complete the operation (in an OR sentence it would be the first non-false value, in an AND sentence it would be the last one). If the operation fails, then falseis returned.
这是可能的,因为 JavaScript 中的逻辑运算符不返回布尔值,而是返回完成操作所需的最后一个元素的值(在 OR 语句中它将是第一个非假值,在 AND 语句中它将是最后一个)。如果操作失败,则false返回。

