What is the purpose of a plus symbol before a variable?

后端 未结 4 1745
死守一世寂寞
死守一世寂寞 2020-11-22 09:39

this really sounds like a simple question but I had no luck searching. what does the +d in

function addMonths(d, n, keepTime) { 
    if (+d) {
         


        
相关标签:
4条回答
  • 2020-11-22 10:15

    Operator + is a unary operator which converts value to number. Below I prepared a table with corresponding results of using this operator for different values.

    +-----------------------------+-----------+
    | Value                       | + (Value) |
    +-----------------------------+-----------+
    | 1                           | 1         |
    | '-1'                        | -1        |
    | '3.14'                      | 3.14      |
    | '3'                         | 3         |
    | '0xAA'                      | 170       |
    | true                        | 1         |
    | false                       | 0         |
    | null                        | 0         |
    | 'Infinity'                  | Infinity  |
    | 'infinity'                  | NaN       |
    | '10a'                       | NaN       |
    | undefined                   | Nan       |
    | ['Apple']                   | Nan       |
    | function(val){ return val } | NaN       |
    +-----------------------------+-----------+
    

    Operator + returns value for objects which have implemented method valueOf.

    let something = {
        valueOf: function () {
            return 25;
        }
    };
    
    console.log(+something);
    
    0 讨论(0)
  • 2020-11-22 10:18

    As explained in other answers it converts the variable to a number. Specially useful when d can be either a number or a string that evaluates to a number.

    Example (using the addMonths function in the question):

    addMonths(34,1,true);
    addMonths("34",1,true);
    

    then the +d will evaluate to a number in all cases. Thus avoiding the need to check for the type and take different code paths depending on whether d is a number, a function or a string that can be converted to a number.

    0 讨论(0)
  • 2020-11-22 10:29

    It is a unary "+" operator which yields a numeric expression. It would be the same as d*1, I believe.

    0 讨论(0)
  • 2020-11-22 10:36

    The + operator returns the numeric representation of the object. So in your particular case, it would appear to be predicating the if on whether or not d is a non-zero number.

    Reference here. And, as pointed out in comments, here.

    0 讨论(0)
提交回复
热议问题