自增 (++)

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

¥The increment (++) operator increments (adds one to) its operand and returns the value before or after the increment, 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 increment if the operand becomes a BigInt; otherwise, it performs number increment.

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

¥If used postfix, with operator after operand (for example, x++), the increment operator increments and returns the value before incrementing.

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

¥If used prefix, with operator before operand (for example, ++x), the increment operator increments and returns the value after incrementing.

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

¥The increment 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 increment operators together.

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

示例

¥Examples

后缀增量

¥Postfix increment

js
let x = 3;
const y = x++;
// x is 4; y is 3

let x2 = 3n;
const y2 = x2++;
// x2 is 4n; y2 is 3n

前缀增量

¥Prefix increment

js
let x = 3;
const y = ++x;
// x is 4; y is 4

let x2 = 3n;
const y2 = ++x2;
// x2 is 4n; y2 is 4n

规范

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

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看