Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/438.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/73.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
JavaScript中的逻辑运算符及其行为_Javascript_Jquery_Logic_Operators_Logical Operators - Fatal编程技术网

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

JavaScript中的逻辑运算符及其行为,javascript,jquery,logic,operators,logical-operators,Javascript,Jquery,Logic,Operators,Logical Operators,为什么会失败 我阅读这段代码的方式是,如果a、b或c等于3,则该语句为真。但显然JavaScript不同意。为什么? function test() { var a = 'one'; var b = 'two'; var c = 'three'; return ( ( a || b || c ) === 'three' ); } 编辑:我知道我需要分别计算每个表达式,但我正在寻找一种更快的方法来编写它。欢迎您提供任何建议。您对代码的阅读不正确。翻译成另一种

为什么会失败

我阅读这段代码的方式是,如果a、b或c等于3,则该语句为真。但显然JavaScript不同意。为什么?

function test() {

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

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

}

编辑:我知道我需要分别计算每个表达式,但我正在寻找一种更快的方法来编写它。欢迎您提供任何建议。

您对代码的阅读不正确。翻译成另一种形式:

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

子表达式a | | b | c返回a、b或c中第一个不是falsy的。这是a,因为它的值是1,所以这是与3相比较的总值。

这计算结果是a、b或c,它将是真或假,相当于3的字符串。这永远是错误的。 为了实现你想要的,你需要

return (a === 'three') || (b === 'three') || (c === 'three');
表达式a | | b | c根据先到先得的原则返回任何真实的内容。 这里a是真实的,因此被使用。如果a为假,将使用b。如果它也是假的,将使用c

因此,由于字符串被认为是真实的,所以最终总是比较1==3。在本例中,您可以使用Array.some,用您的话来说,它做您想要做的事情,或者您想要它的行为方式

如果a或b或c等于3,则该语句为真


谢谢你的解释。现在这是有道理的。是否有任何方法可以实现类似于我发布的内容?我知道我需要分别计算每个表达式,但我正在寻找一种更快的方法来编写它。任何建议都是受欢迎的。@goodpixels好吧,没有一个真正的方法可以做到这一点,这不是有点笨拙。你必须对每一个进行明确的比较。我想你可以将它们包装成一个数组,然后使用.indexOf,但这看起来很笨拙,也不太明显。
return [a,b,c].some(function(str){
   return str == "three";
});