What does = +_ mean in JavaScript

前端 未结 12 1875
南笙
南笙 2020-11-22 11:37

I was wondering what the = +_ operator means in JavaScript. It looks like it does assignments.

Example:

hexbin.radius = function(_)         


        
12条回答
  •  天涯浪人
    2020-11-22 12:35

    r = +_;
    
    • + tries to cast whatever _ is to a number.
    • _ is only a variable name (not an operator), it could be a, foo etc.

    Example:

    +"1"
    

    cast "1" to pure number 1.

    var _ = "1";
    var r = +_;
    

    r is now 1, not "1".

    Moreover, according to the MDN page on Arithmetic Operators:

    The unary plus operator precedes its operand and evaluates to its operand but attempts to converts it into a number, if it isn't already. [...] It can convert string representations of integers and floats, as well as the non-string values true, false, and null. Integers in both decimal and hexadecimal ("0x"-prefixed) formats are supported. Negative numbers are supported (though not for hex). If it cannot parse a particular value, it will evaluate to NaN.

    It is also noted that

    unary plus is the fastest and preferred way of converting something into a number

提交回复
热议问题