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

浏览器兼容性

另见