JavaScript - TypedArray lastIndexof() 方法
JavaScript TypedArray lastIndexOf() 方法在类型化数组中从右到左搜索指定的 searchElement。该方法返回 searchElement 最后一次出现的索引,如果未找到则返回 -1。
假设指定的 searchElement 在类型化数组中仅出现一次,则此方法返回从 第 0 个索引开始的索引。如果 searchElement 出现多次,则优先返回最后一个元素。
语法
以下是 JavaScript TypedArraylastIndexof() 方法的语法 -
lastIndexOf(searchElement, fromIndex)
参数
此方法接受两个参数,分别为"searchElement"和"fromIndex"。参数说明如下:
searchElement − 需要在类型数组中搜索的元素。
fromIndex − 从零开始的索引,表示从末尾开始搜索的位置。
返回值
此方法返回类型数组中 searchElement 的最后一个索引。如果搜索元素不存在,则返回 -1。
示例
示例 1
如果省略 fromIndex 参数,仅传递 searchElement 参数,则该方法将返回指定 searchElement 从 TypedArray 末尾开始的最后一个索引。
在以下示例中,我们使用 JavaScript TypedArray 方法 lastIndexOf() 检索类型数组 [10, 20, 30, 40, 30, 50, 60] 中指定 searchElement 30 的最后一个索引。
<html>
<head>
<title>JavaScript TypedArray lastIndexof() Method</title>
</head>
<body>
<script>
const T_array = new Uint8Array([10, 20, 30, 30, 40, 50, 60]);
document.write("Original typed array: ", T_array);
const serachElement = 30;
document.write("<br>Search element: ", serachElement);
document.write("<br>The element ", serachElement, " found at the last index ", T_array.lastIndexOf(serachElement));
</script>
</body>
</html>
输出
上述程序返回元素 30 最后一次出现的索引为 3。
Original typed array: 10,20,30,30,40,50,60 Search element: 30 The element 30 found at the last index 3
示例 2
如果我们同时将 'searchElement' 和 'fromIndex' 参数传递给此方法,它将返回从指定 fromIndex 开始的元素的最后一个索引。
以下是 JavaScript TypedArray lastIndexOf() 方法的另一个示例。我们使用此方法检索指定元素 6 的最后一个索引,从索引 5 开始搜索,此类型数组为:[1, 2, 4, 6, 8, 9, 6, 11]。
<html>
<head>
<title>JavaScript TypedArray lastIndexof() Method</title>
</head>
<body>
<script>
const T_array = new Uint8Array([1, 2 , 4, 6, 8, 9, 6, 11]);
document.write("Original typed array: ", T_array);
const serachElement = 6;
const fromIndex = 5;
document.write("<br>Search element: ", serachElement);
document.write("<br>From index: ", fromIndex);
document.write("<br>The element ", serachElement, " found at the last index ", T_array.lastIndexOf(serachElement, fromIndex));
</script>
</body>
</html>
输出
执行程序后,返回元素 6 最后一次出现的索引为 3。
Original typed array: 1,2,4,6,8,9,6,11 Search element: 6 From index: 5 The element 6 found at the last index 3
示例 3
如果在此类型数组中未找到指定的 searchElement,则返回 -1。
在此示例中,我们在类型数组上使用类型数组的 lastIndexOf() 方法,检索给定类型数组 [1, 3, 5, 7, 13] 中 searchElement 11 的最后一个索引。
<html>
<head>
<title>JavaScript TypedArray lastIndexof() Method</title>
</head>
<body>
<script>
const T_array = new Uint8Array( [1, 3, 5, 7, 13]);
document.write("Original typed array: ", T_array);
const serachElement = 6;
document.write("<br>Search element: ", serachElement);
document.write("<br>The element ", serachElement, " found at the last index ", T_array.lastIndexOf(serachElement));
</script>
</body>
</html>
输出
上述程序执行后将返回 -1。
Original typed array: 1,3,5,7,13 Search element: 6 The element 6 found at the last index -1

