JS逻辑运算符

JS logical operators

本文关键字:逻辑运算符 JS      更新时间:2023-09-26
var 
            type = 'foo',
            type2 = 'bar',
            result = 0;
        type == 'foo' && result++;
        console.log(result); // 1
        !type == 'foo' || result++;
        console.log(result); // 2
        type == 'foo' && type2 == 'bar' && result++;
        console.log(result); //3
        type == 'foo' && type2 == 'bar' && result == 3 && (result=0); //parentheses avoid "invalid assignment left-hand side" error
        console.log(result); //0
        type == 'OOF' || result++; //equivalent: type != 'OOF' && result++;
        console.log(result); //1    

它以什么顺序工作?

            type == 'foo' && result++;
        !type == 'foo' || result++;

全文(https://github.com/shichuan/javascript-模式/斑点/主/一般-patterns/conditionals.html)

让我们分解一下:

type == 'foo' && result++;

由于短路评估,第二部分result++只有在type == 'foo'时才进行评估。 相当简单的案例,对吧? 让我们看一下第二个条件:

!type == 'foo' || result++;

这可能不会像您认为的那样。 您正在将类型评估为布尔值,在这种情况下,任何非空字符串都将返回 true。 你否定了这个值,所以你会得到假。 将错误与'foo'进行比较会让你变得错误。 为了短路该表达式,第一部分必须是真的,但它是假的,所以简而言之,result++将始终被评估。

您可能的意思如下:

!(type == 'foo') || result++

或者同样可以接受:

type != 'foo' || result++

让我们看一下以下内容:

type == 'foo' && type2 == 'bar' && result == 3 && (result=0)

如果类型为 foo,则它计算下一部分,因此type2 == 'bar' . 如果这也是真的,那么它将评估result == 3 . 如果这是真的,则结果将分配给 0,因为您没有检查等价性。 因此,从本质上讲,如果类型为"foo",类型2为"bar",结果为3,则将结果设置为0。

了解它的工作原理很重要,但永远不要在实际代码中的条件中添加增量或赋值语句。 众所周知,即使您写了它,如果自您编写以来已经过去了足够的时间,它们也很难发现。

希望有帮助。