Atomics.compareExchange()

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.compareExchange() メソッドは、指定された値を配列内の指定した位置に格納し、その値を返します。これは、その位置での古い値が、期待された値と同じであったかどうかを返すものです。これは不可分操作で、変更された値が書き戻されるまで、他の書き込みが行われないことが保証されます。

試してみましょう

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

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

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

構文

js
Atomics.compareExchange(typedArray, index, expectedValue, replacementValue);

引数

typedArray

共有整数の型付き配列です。 Int8Array, Uint8Array, Int16Array, Uint16Array, Int32Array, Uint32Array の何れかです。

index

typedArrayvalue と交換する位置です。

expectedValue

等価性をチェックする値です。

replacementValue

交換する数値です。

返値

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

例外

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

compareExchange() の使用

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

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

仕様書

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

ブラウザーの互換性

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
compareExchange

Legend

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

Full support
Full support

関連情報