Atomics.xor()

Baseline 已廣泛支援

此功能已成熟,可在多種裝置和瀏覽器版本上使用。自 2021 年 12 月以來,它已在所有瀏覽器中可用。

Atomics.xor() 靜態方法在陣列的指定位置與給定值進行按位異或運算,並返回該位置的舊值。此原子操作保證在修改後的值寫回之前,不會發生其他寫入操作。

試一試

// Create a SharedArrayBuffer with a size in bytes
const buffer = new SharedArrayBuffer(16);
const uint8 = new Uint8Array(buffer);
uint8[0] = 7;

// 7 (0111) XOR 2 (0010) = 5 (0101)
console.log(Atomics.xor(uint8, 0, 2));
// Expected output: 7

console.log(Atomics.load(uint8, 0));
// Expected output: 5

語法

js
Atomics.xor(typedArray, index, value)

引數

typedArray

一個整數型別化陣列。可以是 Int8ArrayUint8ArrayInt16ArrayUint16ArrayInt32ArrayUint32ArrayBigInt64ArrayBigUint64Array 中的一種。

index

typedArray 中進行按位異或運算的位置。

value

與給定值進行按位異或運算的數字。

返回值

給定位置(typedArray[index])上的舊值。

異常

TypeError

如果 typedArray 不是允許的整數型別之一,則丟擲。

RangeError

如果 indextypedArray 中超出界限,則丟擲。

描述

如果 ab 不同,則按位異或運算的結果為 1。異或運算的真值表為:

a b a ^ b
0 0 0
0 1 1
1 0 1
1 1 0

例如,按位異或運算 5 ^ 1 的結果是 0100,即十進位制的 4。

5  0101
1  0001
   ----
4  0100

示例

使用 xor

js
const sab = new SharedArrayBuffer(1024);
const ta = new Uint8Array(sab);
ta[0] = 5;

Atomics.xor(ta, 0, 1); // returns 5, the old value
Atomics.load(ta, 0); // 4

規範

規範
ECMAScript® 2026 語言規範
# sec-atomics.xor

瀏覽器相容性

另見