原子学。JavaScript中的xor()

什么是原子学? 原子是JavaScript中的一个对象,它提供作为静态方法执行的原子操作。就像JavaScript中的Math对象一样,原子的所有属性和方法也是静态的。 原子与SharedArrayBuffer(通用固定长度二进制数据缓冲区)对象一起使用。原子不像其他全局对象那样是构造器。原子不能与新操作符一起使用,也不能作为函数调用。 JavaScript中的原子操作 当存在共享内存时,多个线程可以在内存中读写相同的数据。为了确保准确地写入和读取预测值,在当前操作完成之前,另一个操作无法启动。原子操作也不能被中断。 原子学。and()方法 在原子操作中,有一种方法 原子学。xor() 用于在数组中的给定位置计算具有给定值的按位异或运算。该位置的旧值由原子返回。xor()函数。在回写修改后的值之前,不能执行其他写入操作。 语法:

null
Atomics.xor(typedArray, index, value)

使用的参数:

  1. typedarray:它是要修改的共享整数类型数组。
  2. 索引:它是类型Darray中要计算位异或的位置。
  3. 值:它是要计算按位异或的数字。

返回值: 原子学。xor()返回给定位置的旧值(typedArray[index])。 下面提供了上述功能的示例。 例如:

Input : arr[0] = 9;        Atomics.xor(arr, 0, 3);Output : 9Input : arr[0] = 3;         Atomics.xor(arr, 0, 2);Output : 3

下面提供了上述功能的代码。 代码1:

html

< script >
<!-- creating a SharedArrayBuffer -->
var buf = new SharedArrayBuffer(25);
var arr = new Uint8Array(buf);
<!-- Initialising element at zeroth position of array with 9 -->
arr[0] = 9;
<!-- 9 (1001) OR 3 (0011) =  10 (1010) -->
<!-- Displaying the return value of the Atomics.xor() method -->
console.log(Atomics.xor(arr, 0, 3));
<!-- Displaying the updated SharedArrayBuffer -->
console.log(Atomics.load(arr, 0));
</ script >


输出:

910

代码2:

html

< script >
<!-- creating a SharedArrayBuffer -->
var buf = new SharedArrayBuffer(25);
var arr = new Uint8Array(buf);
<!-- Initialising element at zeroth position of array with 3 -->
arr[0] = 3;
<!-- 3 (0011) AND 2 (0010) =  3 (0001) -->
<!-- Displaying the return value of the Atomics.xor() method -->
console.log(Atomics.xor(arr, 0, 2));
<!-- Displaying the updated SharedArrayBuffer -->
console.log(Atomics.load(arr, 0));
</ script >


输出:

31

例外情况:

  • 如果typedArray不是允许的整数类型之一,则引发TypeError。
  • 如果typedArray不是共享类型的数组类型,则引发TypeError。
  • 如果索引超出typedArray中的界限,则抛出RangeError。

支持的浏览器:

  • 谷歌浏览器
  • 微软边缘
  • 火狐
© 版权声明
THE END
喜欢就支持一下吧
点赞6 分享