JavaScript TypedArray lastIndexOf() 方法从右到左在类型化数组中搜索指定的 searchElement。它返回 searchElement 最后一次出现的索引,如果未找到,则返回 -1。
假设指定的 searchElement 在类型化数组中只存在一次,则此方法返回从第 0 个索引开始的索引。如果 searchElement 多次出现,它将优先于最后一个元素。
语法
以下是 JavaScript TypedArraylastIndexof() 方法的语法 -
lastIndexOf(searchElement, fromIndex)
参数
此方法接受两个参数,即 'searchElement' 和 'fromIndex'。参数如下所述 -
- searchElement − 需要在类型化数组中搜索的元素。
- fromIndex − 从零开始的索引表示从末尾开始搜索的位置。
返回值
此方法返回类型化数组中 searchElement 的最后一个索引。如果 search 元素不存在,则返回 −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。
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。
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。
Search element: 6
The element 6 found at the last index -1