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

后端 未结 4 1744
死守一世寂寞
死守一世寂寞 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);
    

提交回复
热议问题