遞增 (++)
遞增 (++) 運算子遞增(給其運算元加一)其運算元,並根據運算子的位置,返回遞增前或遞增後的值。
試一試
let x = 3;
const y = x++;
console.log(`x:${x}, y:${y}`);
// Expected output: "x:4, y:3"
let a = 3;
const b = ++a;
console.log(`a:${a}, b:${b}`);
// Expected output: "a:4, b:4"
語法
js
x++
++x
描述
++ 運算子對兩種型別的運算元進行了過載:number 和 BigInt。它首先將 運算元強制轉換為數值 並測試其型別。如果運算元變為 BigInt,則執行 BigInt 遞增;否則,執行 number 遞增。
如果用作字尾,即運算子在運算元之後(例如 x++),則遞增運算子遞增並返回遞增前的值。
如果用作字首,即運算子在運算元之前(例如 ++x),則遞增運算子遞增並返回遞增後的值。
遞增運算子只能應用於作為引用的運算元(變數和物件屬性;即有效的賦值目標)。++x 本身評估為一個值,而不是一個引用,因此你不能將多個遞增運算子連結在一起。
js
++(++x); // SyntaxError: Invalid left-hand side expression in prefix operation
示例
字尾遞增
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
字首遞增
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
規範
| 規範 |
|---|
| ECMAScript® 2026 語言規範 # sec-postfix-increment-operator |
瀏覽器相容性
載入中…