JavaScript - TypedArray at() 方法
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
示例 2
如果索引值传递为 -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
示例 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);
//调用函数s
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

