javascript 一元加减运算符的重要用途是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5450076/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 17:14:06  来源:igfitidea点击:

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

javascript

提问by dragonfly

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

如果使用一元+/-运算符来执行转换作为Number()转换函数,那么我们为什么需要一元运算符?这些一元运算符有什么特殊需要?

回答by Ben Zotto

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)

一元+运算符将其操作数转换为数字类型。一元-运算符将其操作数转换为 Number 类型,然后将其取反。(根据ECMAScript 规范

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.

这就是工作中的一元减号运算符。+正如规范所暗示的那样,一元等同于作为函数调用的 Number() 构造函数。

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.

我只能推测历史,但一元 +/- 运算符在许多 C 派生语言中的行为相似。我怀疑 Number() 行为是这里语言的补充。