一元否定 (-)

一元否定 (-) 运算符位于其操作数之前并对它求反。

¥The unary negation (-) operator precedes its operand and negates it.

Try it

语法

¥Syntax

js
-x

描述

¥Description

- 运算符针对两种类型的操作数进行重载:编号和 BigInt。它首先 将操作数强制为数值 并测试它的类型。如果操作数变为 BigInt,则执行 BigInt 求反;否则,执行数字求反。

¥The - operator is overloaded for two types of operands: number and BigInt. It first coerces the operand to a numeric value and tests the type of it. It performs BigInt negation if the operand becomes a BigInt; otherwise, it performs number negation.

示例

¥Examples

对数字求反

¥Negating numbers

js
const x = 3;
const y = -x;
// y is -3; x is 3

否定非数字

¥Negating non-numbers

一元否定运算符可以将非数字转换为数字。

¥The unary negation operator can convert a non-number into a number.

js
const x = "4";
const y = -x;

// y is -4

BigInt 可以使用一元否定运算符进行否定。

¥BigInts can be negated using the unary negation operator.

js
const x = 4n;
const y = -x;

// y is -4n

规范

Specification
ECMAScript Language Specification
# sec-unary-minus-operator

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看