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 2021年12月.
Atomics.xor() は静的メソッドで、配列内の指定した位置にある指定された値とのビット単位の XOR を計算し、その位置にあった古い値を返します。これは不可分操作であり、変更された値が書き戻されるまで他の書き込みが行われないことが保証されます。
試してみましょう
// バイト単位でサイズを指定して SharedArrayBuffer を作成
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));
// 予想される結果: 7
console.log(Atomics.load(uint8, 0));
// 予想される結果: 5
構文
js
Atomics.xor(typedArray, index, value)
引数
typedArray-
整数の型付き配列です。
Int8Array、Uint8Array、Int16Array、Uint16Array、Int32Array、Uint32Array、BigInt64Array、BigUint64Arrayのいずれかです。 index-
typedArrayの中でビット単位の XOR を計算する位置です。 value-
ビット単位の XOR を計算する値です。
返値
指定された位置にあった古い値 (typedArray[index]) です。
例外
TypeError-
typedArrayが許可された整数型のいずれでもない場合に発生します。 RangeError-
indexがtypedArrayの範囲を超えている場合に発生します。
解説
ビット単位の XOR 演算は、 a と b が異なる場合に 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® 2026 Language Specification> # sec-atomics.xor> |
ブラウザーの互換性
Loading…