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
廣告