javascript javascript中的逻辑运算符&&和两个字符串

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

Logical operator && and two strings in javascript

javascriptstringoperators

提问by Ashesh

When I use the logical operator && between two strings, why does it give me the second string as output:

当我在两个字符串之间使用逻辑运算符 && 时,为什么它给我第二个字符串作为输出:

console.log("" && "Dog");    // ""
console.log("Cat" && "Dog"); // "Dog"

I realize that the with the exception of 0, false, null, undefined, ""and NaN, everything else is evaluated as a boolean true in a logical expression like the one above. But why is the output the second string and not the first? And why is the ouput not just "true" since it is being evaluated as a boolean expression?

我意识到除了0, false, null, undefined,""和 之外NaN,其他所有内容都在上面的逻辑表达式中被评估为布尔值 true。但是为什么输出是第二个字符串而不是第一个?为什么输出不只是“真”,因为它被评估为布尔表达式?

采纳答案by Thank you

in the expression

在表达式中

"Cat" && "Dog"
// => "Dog"

Because you're using &&, JavaScript is promising you that it will verify that both sides of the expression are true. In this case, "Dog"is the just the last evaluated thing.

因为您使用的是&&,JavaScript 向您保证它会验证表达式的两边都是true。在这种情况下,"Dog"是最后一个评估的东西。

To be more explicit, you could do something like

更明确地说,你可以做类似的事情

var c = "Cat" != null && "Dog" != null

It's a little bit more wordy, but this boils down to

它有点罗嗦,但这归结为

var c = true && true
console.log(c)
// => true

If you want a simple shortcut for the boolean, use the Booleanconstructor -

如果您想要布尔值的简单快捷方式,请使用Boolean构造函数 -

var c = Boolean("Cat" && "Dog")
console.log(c)
// => true

If you just use a simple REPL or JavaScript console, you'd be able to see this output very easily.

如果您只使用简单的 REPL 或 JavaScript 控制台,您将能够非常轻松地看到此输出。



Per one of the comments below

根据以下评论之一

Using ||, JavaScript is promising you that at least oneof the sides is true. Since "Cat" is true, it stops there and returns "Cat". This is known as Short-circuit evaluation

使用||,JavaScript 向您保证至少有一个方面是true。由于“Cat”为真,它停在那里并返回“Cat”。这称为短路评估

回答by José Ernesto Lara Rodríguez

Answer by @naomik pretty much covers it. If you want to go deep, I suggest taking a look at the ECMAScript specification, section 11.11:

@naomik 的回答几乎涵盖了它。如果你想深入,我建议看一下 ECMAScript 规范,第 11.11 节:

http://www.ecma-international.org/ecma-262/5.1/#sec-11.11

http://www.ecma-international.org/ecma-262/5.1/#sec-11.11

In the "Semantics" section, we can see:

在“语义”部分,我们可以看到:

The production LogicalANDExpression: LogicalANDExpression&& BitwiseORExpressionis evaluated as follows:

  1. Let lrefbe the result of evaluating LogicalANDExpression.
  2. Let lvalbe GetValue(lref).
  3. If ToBoolean(lval) is false, return lval.
  4. Let rrefbe the result of evaluating BitwiseORExpression.
  5. Return GetValue(rref).

产生式LogicalANDExpression: LogicalANDExpression&& BitwiseORExpression计算如下:

  1. lref是评估LogicalANDExpression的结果。
  2. lval为 GetValue( lref)。
  3. 如果 ToBoolean( lval) 为假,则返回lval
  4. rref是计算BitwiseORExpression的结果。
  5. 返回 GetValue( rref)。

回答by Matti Mehtonen

I think this is because of nature of logical operator &&. Javascript executes expression "cat" && "Dog"in following way:

我认为这是因为逻辑运算符 && 的性质。Javascript"cat" && "Dog"通过以下方式执行表达式:

Checks the value "cat" - it returns something else than "", 0, null, undefined or false and is truthy. Javascript sees &&and so it continues expression and faces string "Dog", which is something else than "", 0, null, undefined or false and is truthy, expression ends and expression returns the last value it checked.

检查值“cat” - 它返回除“”、0、null、undefined 或 false 之外的其他值,并且是真的。Javascript看到&&,所以它继续表达并面对字符串“Dog”,它不是“”,0,空,未定义或假的东西,并且是真实的,表达式结束并且表达式返回它检查的最后一个值。

If you replace &&with ||expressions ends at first truthy value and thats way

如果你&&||表达式替换,以第一个真值结束,就是这样

var boolean = "cat" ||?"dog"

returns first value: cat

返回第一个值: cat

回答by FrancescoMM

Because of the way logic works, if you need to test if both items are true, and you already know the first item is true, then the test totally depends on the second item.

由于逻辑的工作方式,如果您需要测试两项是否为真,并且您已经知道第一项为真,那么测试完全取决于第二项。

true && someValue is equivalent to just someValue

true && someValue 等价于 someValue

For this reason, the operator && can be handled by returning its operands instead of true/false values, and just testing the first operand and not the second

出于这个原因,运算符 && 可以通过返回其操作数而不是真/假值来处理,并且只测试第一个操作数而不是第二个操作数

a && b:

一个&& b:

  • if a evaluates to false, no need to test further, return a (as it's false)

  • else if a evaluates to true, the result totally depends on b, so just return b (no need to test if b evaluates to true or false, just return it)

  • 如果 a 评估为假,则无需进一步测试,返回 a (因为它是假的)

  • 否则如果 a 评估为真,结果完全取决于 b,所以只返回 b (无需测试 b 评估为真或假,只需返回它)

In code this is like

在代码中,这就像

function and(a,b) {
    if(!a) return a;
    return b;
}

Similarly operator || can be defined as

类似的操作符 || 可以定义为

function or(a,b) {
    if(a) return a;
    return b;
}

Returning operands instead of true/false has a few advantages:

返回操作数而不是真/假有几个优点:

  • requires less evaluations (notice b is never evaluated, in both cases)

  • does not require a definition of true/false so it works more broadly, even cross language or if the value of "true" changes

  • can be "hacked" to be used, without an if, to do stuff like string1 && string2 that has a useful meaning: "if string1 is not empty use string2 otherwise keep it empty (to replace every word of a string with the text "word": aString.split(" ").map(function(word) {return word && "word"});

  • 需要较少的评估(注意 b 永远不会被评估,在这两种情况下)

  • 不需要真/假的定义,因此它的工作范围更广,甚至跨语言或“真”的值发生变化

  • 可以在没有 if 的情况下“破解”使用,以执行诸如 string1 && string2 之类的具有有用意义的事情:“如果 string1 不为空,则使用 string2 否则将其保持为空(用文本替换字符串中的每个单词”单词”: aString.split(" ").map(function(word) {return word && "word"});

JavaScripters love that kind of stuff (exploiting one operator side effect out of the usual context to get a different, unexpected behaviour), they do this to show off language knowlodge at parties. :D

JavaScript 开发者喜欢这种东西(在通常的上下文之外利用一个运算符的副作用来获得不同的、意想不到的行为),他们这样做是为了在聚会上炫耀语言知识。:D