在线文档教程

Atomics.compareExchange

Atomics.compareExchange

Atomics.compareExchange()静态方法会在数组的值与期望值相等的时候,将给定的替换值替换掉数组上的值,然后返回旧值。此原子操作保证在写上修改的值之前不会发生其他写操作。

语法

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

参数

typedArray一个共享的整型 typed array。例如 Int8ArrayUint8ArrayInt16ArrayUint16ArrayInt32Array,或Uint32ArrayindextypedArray 的索引。expectedValue用于比较的值。replacementValue将要替换上的值。

返回值

给定位置的旧值(typedArray[index]).

异常

  • 假如 typedArray 不是允许的整型之一,则抛出 TypeError

  • 假如 typedArray 不是一个贡献的 typed array,则抛出 TypeError

  • 如果 index 超出了 typedArray 的边界,则抛出 RangeError

示例

var sab = new SharedArrayBuffer(1024 var ta = new Uint8Array(sab ta[0] = 7; Atomics.compareExchange(ta, 0, 7, 12 // returns 7, the old value Atomics.load(ta, 0 // 12

规范

SpecificationStatusComment
ECMAScript Latest Draft (ECMA-262)The definition of 'Atomics.compareExchange' in that specification.Living StandardInitial definition in ES2017.

浏览器兼容性

FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic supportNo support 2No support55 (55) 1No supportNo supportNo support

FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic supportNo supportNo support55.0 (55) 1No supportNo supportNo support