Atomics.xor()

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since December 2021.

Atomics.xor() は静的メソッドで、配列内の指定した位置にある指定された値とのビット単位の 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 の中でビット単位の XOR を計算する位置です。

value

ビット単位の XOR を計算する値です。

返値

指定された位置にあった古い値 (typedArray[index]) です。

例外

  • TypeError: typedArray が許可されている整数の型ではなかった場合に発生します。
  • RangeError: indextypedArray の範囲を超えていた場合に発生します。

解説

ビット単位の XOR 演算は、 ab が異なる場合に 1 になります。 XOR 演算の真理値表は次の通りです。

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

例えば、ビット単位の XOR では 5 ^ 1 の結果が 0100、すなわち 10 進数で 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); // 古い値である 5 を返す
Atomics.load(ta, 0); // 4

仕様書

Specification
ECMAScript® 2025 Language Specification
# sec-atomics.xor

ブラウザーの互換性

Report problems with this compatibility data on GitHub
desktopmobileserver
Chrome
Edge
Firefox
Opera
Safari
Chrome Android
Firefox for Android
Opera Android
Safari on iOS
Samsung Internet
WebView Android
WebView on iOS
Deno
Node.js
xor

Legend

Tip: you can click/tap on a cell for more information.

Full support
Full support

関連情報