Atomics.exchange()

Baseline 已廣泛支援

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

Atomics.exchange() 靜態方法用於在陣列中的給定位置交換一個給定的值,並返回該位置上的舊值。此原子操作保證在讀取舊值和寫入新值之間不會發生其他寫入操作。

試一試

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

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

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

語法

js
Atomics.exchange(typedArray, index, value)

引數

typedArray

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

index

要在 typedArray 中交換 value 的位置。

value

要交換的數字。

返回值

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

異常

TypeError

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

RangeError

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

示例

使用 exchange()

js
const sab = new SharedArrayBuffer(1024);
const ta = new Uint8Array(sab);

Atomics.exchange(ta, 0, 12); // returns 0, the old value
Atomics.load(ta, 0); // 12

規範

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

瀏覽器相容性

另見