+!! operator in an if statement

后端 未结 6 2028
旧巷少年郎
旧巷少年郎 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:07

    This is a horribly unreadable way to write out the boolean value of a variable, and then convert it using unary conversion to give a 0/1 number result.

    Consider:

    +!!true; //this converts true to false, then to true again, and true is 1 when converted
    +!!0; //converts 0 (falsy) to true, then false, and then the numeric 0
    

    Technically speaking !! is not its own operator, it's just the NOT (!) operator twice.

    Unary conversion: ECMA spec doc a unary plus attempts to convert to an integer. Number() would also be a valid conversion.

提交回复
热议问题