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

© . All rights reserved.