JavaScript TypedArray at() 方法用于检索指定位置(或索引)处的类型化数组元素。它允许正索引值和负索引值,其中正索引从头开始计数,负索引从末尾开始计数。
例如,索引值 -1 表示最后一个元素,而 0 索引值表示类型化数组中的第一个元素。
语法
以下是 JavaScript TypedArray at() 方法的语法 -
at(index)
参数
此方法接受一个名为 'index' 的参数,如下所述 -
- index − 返回类型化元素的从零开始的索引。
返回值
此方法返回在指定索引处找到的类型化数组元素。
示例 1
如果我们将索引值作为 2 传递,它将从头开始计数(从第 0 个索引开始)并返回类型化数组中的第三个元素。
在下面的示例中,我们使用 JavaScript TypedArray at() 方法检索此类型化数组 [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
Index: 2
The index 2 represents the element 3
示例 2
如果 index 值作为 -1 传递,它将返回类型化数组的最后一个元素。
以下是 JavaScript TypedArray at() 方法的另一个示例。我们使用此方法检索此类型化数组 [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>
输出
执行上述程序后,它将返回类型化数组的最后一个元素为 -
Typed array: 10,20,30,40,50
Index: -1
The index -1 represents the element 50
Index: -1
The index -1 represents the element 50
示例 3
在给定的示例中,我们创建了一个名为 returnSecondLast() 的函数,该函数接受类型化数组作为参数。我们在这个函数中使用 at() 方法来检索这个类型化数组 [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
Second last element: 40