减量 (--)

递减 (--) 运算符对其操作数进行递减(减一),并返回递减之前或之后的值,具体取决于运算符放置的位置。

¥The decrement (--) operator decrements (subtracts one from) its operand and returns the value before or after the decrement, depending on where the operator is placed.

Try it

语法

¥Syntax

js
x--
--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 decrement if the operand becomes a BigInt; otherwise, it performs number decrement.

如果使用后缀,操作数后带有运算符(例如,x--),则减量运算符将减量并返回减量之前的值。

¥If used postfix, with operator after operand (for example, x--), the decrement operator decrements and returns the value before decrementing.

如果使用前缀,操作数之前有运算符(例如 --x),则减量运算符会减 1,并返回减 1 后的值。

¥If used prefix, with operator before operand (for example, --x), the decrement operator decrements and returns the value after decrementing.

减量运算符只能应用于作为引用的操作数(变量和对象属性;即有效的 分配目标)。--x 本身计算为一个值,而不是一个引用,因此你不能将多个减量运算符链接在一起。

¥The decrement operator can only be applied on operands that are references (variables and object properties; i.e. valid assignment targets). --x itself evaluates to a value, not a reference, so you cannot chain multiple decrement operators together.

js
--(--x); // SyntaxError: Invalid left-hand side expression in prefix operation

示例

¥Examples

后缀递减

¥Postfix decrement

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

let x2 = 3n;
const y2 = x2--;
// x2 is 2n; y2 is 3n

前缀减量

¥Prefix decrement

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

let x2 = 3n;
const y2 = --x2;
// x2 is 2n; y2 is 2n

规范

Specification
ECMAScript Language Specification
# sec-postfix-decrement-operator

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看