JS逻辑运算符

时间:2016-02-18 11:41:54

标签: javascript

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/blob/master/general-patterns/conditionals.html

1 个答案:

答案 0 :(得分:0)

让我们分解:

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

由于短路评估,第二部分result++仅在type == 'foo'时得到评估。相当直白的情况吧?让我们看看第二个条件:

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

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

您可能意味着以下内容:

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

或同样可以接受:

type != 'foo' || result++

让我们看看以下内容:

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

如果type是foo,那么它会评估下一部分,所以type2 == 'bar'。如果这也是真的,那么它将评估result == 3。如果确实如此,那么结果会将分配设置为0,因为您没有检查等效性。基本上,如果type为'foo'且type2为'bar'且result为3,则将result设置为0.

了解它是如何工作的很重要,但是不要在现实代码的条件中添加增量或赋值语句。众所周知,即使写了它,如果你写完之后有足够的时间,它们也很难被发现。

希望有所帮助。