+!! operator in an if statement

后端 未结 6 2026
旧巷少年郎
旧巷少年郎 2020-12-29 18:31

I was reviewing the code for an angularjs factory to better understand how it works. The code contains an if statement that I don\'t fully understand.

I

6条回答
  •  悲哀的现实
    2020-12-29 19:16

    +!! uses implicit conversion to cast a value as a 0 or 1 depending on its boolean value

    For the most part, this is to check for existence. For example, an empty string is false (!!"" === false), and so is undefined, and a number of others. Those are the main two though

    "Falsey" conversions

    +!!""        ===   0
    +!!false     ===   0
    +!!0         ===   0
    +!!undefined ===   0
    +!!null      ===   0
    +!!NaN       ===   0
    

    "Truthy" conversions

    +!!1         ===   1
    +!!true      ===   1
    +!!"Foo"     ===   1
    +!!3.14      ===   1
    +!![]        ===   1
    +!!{}        ===   1
    

    if ((+!!config.template) + (+!!config.templateUrl) !== 1)

    Hopefully this is making more sense at this point. The object config has two properties we are examining. .template and .templateUrl. The implicit cast to a 0 or 1 using +!! is going to be added and then compared to ensure that it is not 1 (which means it is either 0 or 2) - the properties can either both be on or off but not different.

    The truth table here is as follows:

    template    templateUrl    (+!!) + (+!!)     !==1
    "foo"       "foo"              1 + 1         true
    undefined   undefined          0 + 0         true
    undefined   ""                 0 + 0         true
    ""          undefined          0 + 0         true
    12          ""                 1 + 0         false
    ""          12                 0 + 1         false
    undefined   "foo"              0 + 1         false
    ""          "foo"              0 + 1         false
    "foo"       ""                 1 + 0         false
    "foo"       undefined          1 + 0         false
    

    A much simpler method to all of this would have been to just use the implicit boolean conversion

    if (!config.template === !config.templateUrl)
    

提交回复
热议问题