JavaScript - TypedArray at() 方法



JavaScript TypedArray 的at()方法用於檢索指定位置(或索引)處的 TypedArray 元素。它允許正索引和負索引值,其中正索引從開頭開始計數,負索引從結尾開始計數。

例如,索引值-1表示最後一個元素,而索引值0表示TypedArray中的第一個元素。

語法

以下是 JavaScript TypedArray at() 方法的語法:

at(index)

引數

此方法接受一個名為“index”的引數,如下所述:

  • index - 要返回的 TypedArray 元素的基於零的索引。

返回值

此方法返回在指定索引處找到的 TypedArray 元素。

示例

示例 1

如果我們將索引值作為2傳遞,它將從開頭(從第 0 個索引)開始計數,並返回 TypedArray 中的第三個元素。

在以下示例中,我們使用 JavaScript TypedArray 的at()方法來檢索此 TypedArray [1, 2, 3, 4, 5, 6, 7, 8]中指定位置(索引)2處的元素。

<html>
<head>
   <title>JavaScript TypedArray at() Method</title>
</head>
<body>
   <script>
      const T_array = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]);
      document.write("Typed array: ", T_array);
      const index = 2;
      document.write("<br>Index: ", index);
      document.write("<br>The index ", index, " represents the element ", T_array.at(index));
   </script>
</body>
</html>

輸出

以上程式對於索引值 2 返回 3。

Typed array: 1,2,3,4,5,6,7,8
Index: 2
The index 2 represents the element 3

示例 2

如果索引值作為-1傳遞,它將返回 TypedArray 的最後一個元素。

以下是 JavaScript TypedArray at() 方法的另一個示例。我們使用此方法來檢索此 TypedArray [10, 20, 30, 40, 50]中指定位置-1處的元素。

<html>
<head>
   <title>JavaScript TypedArray at() Method</title>
</head>
<body>
   <script>
      const T_array = new Uint8Array([10, 20, 30, 40, 50]);
      document.write("Typed array: ", T_array);
      const index = -1;
      document.write("<br>Index: ", index);
      document.write("<br>The index ", index, " represents the element ", T_array.at(index));
   </script>
</body>
</html>

輸出

執行以上程式後,它將返回 TypedArray 的最後一個元素,如下所示:

Typed array: 10,20,30,40,50
Index: -1
The index -1 represents the element 50

示例 3

在給定的示例中,我們建立一個名為returnSecondLast()的函式,該函式接受 TypedArray 作為引數。我們在此函式中使用at()方法來檢索此 TypedArray [10, 20, 30, 40, 50]的倒數第二個元素。

<html>
<head>
   <title>JavaScript TypedArray at() Method</title>
</head>
<body>
   <script>
      function returnSecondLast(T_array){
         return T_array.at(-2);
      }
      const T_array = new Uint8Array([10, 20, 30, 40, 50]);
      document.write("TypedArray: ", T_array);
      
      //calling functions
      const secondLast = returnSecondLast(T_array);
      document.write("<br>Second last element: ", secondLast);
   </script>
</body>
</html>

輸出

執行以上程式後,它將返回倒數第二個元素 40。

TypedArray: 10,20,30,40,50
Second last element: 40
廣告