JavaScript - TypedArray 的 with() 方法



JavaScript TypedArray 的with()方法用于更改给定索引的值。它返回一个新的 TypedArray,其中索引处的元素被替换为指定的值。

如果 index 参数值小于或大于 TypedArray 的长度,则此方法会抛出'RangeError'异常。

语法

以下是 JavaScript TypedArray with()方法的语法:

arrayInstance.with(index, value)

参数

  • index - 要替换或更改值的基于零的索引。

  • value - 要在指定索引处插入或分配的值。

返回值

此方法返回一个新的 TypedArray,其中指定索引处的元素被替换为 value。

示例

示例 1

用指定的值替换第一个元素(索引 = 0)的值。

在下面的示例中,我们使用 JavaScript TypedArray 的 with() 方法更改(或替换)此 TypedArray [10, 20, 30, 40, 50] 在指定索引 0 处的元素,将其值更改为 10。

<html>
<head>
   <title>JavaScript TypedArray with() Method</title>
</head>
<body>
   <script>
      const T_array = new Uint8Array([10, 20, 30, 40, 50]);
      document.write("Typed array: ", T_array);
      const index = 0;
      const value = 0;
      document.write("<br>Index: ", index);
      document.write("<br>Value: ", value);
      var new_arr = ([]);
      
      //using with() method
      new_arr = T_array.with(index, value);
      document.write("<br>New typed array after replacing value at specified index: ", new_arr);
   </script>
</body>
</html>

输出

执行上述程序后,它将返回一个新的 TypedArray,替换后的结果为 [0, 20, 30, 40, 50]。

Typed array: 10,20,30,40,50
Index: 0
Value: 0
New typed array after replacing value at specified index: 0,20,30,40,50

示例 2

以下是 JavaScript TypedArray with() 方法的另一个示例。我们使用此方法更改(或替换)此 TypedArray [1, 2, 3, 4, 5, 6, 7] 在指定索引 3 处的元素的值,将其值更改为 10。

<html>
<head>
   <title>JavaScript TypedArray with() Method</title>
</head>
<body>
   <script>
      const T_array = new Uint8Array([1, 2, 3, 4, 5, 6, 7] );
      document.write("Typed array: ", T_array);
      const index = 3;
      const value = 10;
      document.write("<br>Index: ", index);
      document.write("<br>Value: ", value);
      var new_arr = ([]);
      
      //using with() method
      new_arr = T_array.with(index, value);
      document.write("<br>New typed array after replacing value at specified index: ", new_arr);
   </script>
</body>
</html>

输出

上述程序返回一个新的 TypedArray,结果为 [1,2,3,10,5,6,7]。

Typed array: 1,2,3,4,5,6,7
Index: 3
Value: 10
New typed array after replacing value at specified index: 1,2,3,10,5,6,7

示例 3

如果 index 参数值大于 TypedArray 的长度,它将抛出 'RangeError' 异常。

<html>
<head>
   <title>JavaScript TypedArray with() Method</title>
</head>
<body>
   <script>
      const T_array = new Uint8Array([10, 20, 30, 40, 50, 60, 70, 80]);
      document.write("Typed array: ", T_array);
      const index = 10;
      const value = 1;
      document.write("<br>Index: ", index);
      document.write("<br>Value: ", value);
      document.write("<br>Typed array length: ", T_array.length);
      const new_arr = ([]);
      
      try {
         new_arr = T_array.with(index, value);
      } catch (error) {
         document.write("<br>", error);
      }
   </script>
</body>
</html>

输出

执行上述程序后,它将抛出 'RangeError' 异常。

Typed array: 10,20,30,40,50,60,70,80
Index: 10
Value: 1
Typed array length: 8
RangeError: Invalid typed array index
广告

© . All rights reserved.