What's the significant use of unary plus and minus operators?

前端 未结 1 706
清歌不尽
清歌不尽 2020-11-22 07:51

If unary +/- operators are used to perform conversions as the Number() casting function, then why do we need unary operators? What\'s

相关标签:
1条回答
  • 2020-11-22 08:15

    The Unary + operator converts its operand to Number type. The Unary - operator converts its operand to Number type, and then negates it. (per the ECMAScript spec)

    In practice, Unary - is used for simply putting negative numbers in normal expressions, e.g.:

    var x = y * -2.0;
    

    That's the unary minus operator at work. The Unary + is equivalent to the Number() constructor called as a function, as implied by the spec.

    I can only speculate on the history, but the unary +/- operators behave similarly in many C-derived languages. I suspect the Number() behavior is the addition to the language here.

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