What does = +_ mean in JavaScript

前端 未结 12 1730
南笙
南笙 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:24

    In this expression:

    r = +_;
    
    • '+' acts here as an unary operator that tries to convert the value of the right operand. It doesn't convert the operand but the evaluated value. So _ will stay "1" if it was so originally but the r will become pure number.

    Consider these cases whether one wants to apply the + for numeric conversion

    +"-0" // 0, not -0
    +"1" //1
    +"-1" // -1
    +"" // 0, in JS "" is converted to 0
    +null // 0, in JS null is converted to 0
    +undefined // NaN
    +"yack!" // NaN
    +"NaN" //NaN
    +"3.14" // 3.14
    
    var _ = "1"; +_;_ // "1"
    var _ = "1"; +_;!!_ //true
    var _ = "0"; +_;!!_ //true
    var _ = null; +_;!!_ //false
    

    Though, it's the fastest numeric converter I'd hardly recommend one to overuse it if make use of at all. parseInt/parseFloat are good more readable alternatives.

提交回复
热议问题