此页面由社区从英文翻译而来。了解更多并加入 MDN Web Docs 社区。
Atomics.add()
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.add() 静态方法会将给定的值加到数组里的指定位置上,并返回该位置的旧值。此原子操作保证在修改后的值写回之前不会发生其他写操作。
In this article
尝试一下
// Create a SharedArrayBuffer with a size in bytesconst buffer = new SharedArrayBuffer(16);const uint8 = new Uint8Array(buffer);uint8[0] = 7;// 7 + 2 = 9console.log(Atomics.add(uint8, 0, 2));// Expected output: 7console.log(Atomics.load(uint8, 0));// Expected output: 9语法
js
Atomics.add(typedArray, index, value)参数
typedArray一个整数类型数组。
Int8Array、Uint8Array、Int16Array、Uint16Array、Int32Array、Uint32Array、BigInt64Array或BigUint64Array之一。indextypedArray中的要加上value的位置。value要增加的数字。
返回值
给定位置的旧值(typedArray[index])。
异常
TypeError如果
typedArray不是允许的整数类型数组之一,则抛出该异常。RangeError如果
index超出typedArray的范围,则抛出该异常。
示例
>使用 add()
js
const sab = new SharedArrayBuffer(1024);const ta = new Uint8Array(sab);Atomics.add(ta, 0, 12); // 返回 0,即旧的值Atomics.load(ta, 0); // 12规范
| Specification |
|---|
| ECMAScript® 2026 Language Specification> # sec-atomics.add> |