简体   繁体   English

逻辑运算符及其在JavaScript中的行为

[英]Logical operators and their behavior in JavaScript

Why does this fail? 为什么会失败?

The way I read this code is "if either a or b or c equals three, then the statement is true". 我读这段代码的方式是“如果a或b或c等于3,则该陈述为真”。 But apparently JavaScript disagrees. 但显然JavaScript对此表示反对。 Why? 为什么?

function test() {

    var a = 'one';
    var b = 'two';
    var c = 'three';

    return ( ( a || b || c ) === 'three' );

}

EDIT: am aware of the fact that i need to evaluate each expression separately, but was looking for a quicker way to write it. 编辑:知道我需要分别评估每个表达式的事实,但是正在寻找一种更快的方式编写它。 any suggestions will be welcome. 任何建议都将受到欢迎。

Your reading of the code is incorrect. 您对代码的读取不正确。 Translated to a different form: 转换为其他形式:

if (a) {
  return a === "three";
}
if (b) {
  return b === "three";
}
if (c) {
  return c === "three";
}

The subexpression (a || b || c) returns the first of a , b , or c that is not "falsy". 子表达式(a || b || c)返回abc中的第a ,而不是“ falsy”。 That's a , because its value is "one" , so that's the overall value that's compared to "three" . 那是a ,因为它的值是"one" ,所以这是与"three"相比较的整体价值。

The expression ( a || b || c ) returns anything that is truthy on the first-come-first served basis. 表达式( a || b || c )会以先到先得的原则返回任何真实的信息。 Here a is truthy and hence used. 这里a是真实的,因此被使用。 If a is falsey b will be used. 如果a假,则将使用b If it is falsey too, c will be used. 如果也是假的 ,将使用c

So, you always end up comparing "one" == "three" since strings are considered truthy . 因此,由于字符串被认为是true ,所以您最终总是比较"one" == "three" You can make use of Array.some in this case, which does what you want or how you want it to behave, in your words 在这种情况下,您可以使用Array.some ,用您的语言执行您想要的或您希望的行为

"if either a or b or c equals three, then the statement is true" “如果a或b或c等于3,则该陈述为真”

return [a,b,c].some(function(str){
   return str == "three";
});

This evaluates to is a, b, or c (which will be true or false) the string-equivalent of "three". 这等于字符串的等价于“三”的a,b或c(对或错)。 Which will always be false. 这将永远是错误的。 In order to achieve what you want, you need 为了实现您想要的,您需要

return (a === 'three') || (b === 'three') || (c === 'three');

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

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