JavaScript TypedArray findLastIndex() 方法以相反的顺序迭代类型化数组,这意味着类型化数组的最后一个元素将被视为第一个元素,反之亦然。该方法返回满足提供的测试函数的第一个元素(从最后一个开始)的索引。如果类型化数组的元素都不满足 testing 函数,该方法将返回 '−1'。
以下是您应该了解的有关 'findLastIndex()' 方法的一些其他要点 -
- findLastIndex() 方法对 TypedArray(例如 Uint8Array、Int16Array 等)进行操作。
- 它接受 testing 函数作为参数。
- 对 TypedArray 中的每个元素执行 testing 函数。
- 如果元素满足 testing 函数指定的条件(它返回 true 值)。
- 如果没有元素满足,则返回测试函数 −1。
语法
以下是 JavaScript TypedArray findLastIndex() 方法的语法 -
findLastIndex(callbackFn, thisArg)
参数
此方法接受两个名为 'callbackFn' 和 'thisArg' 的参数,如下所述 -
- callbackFn − 此参数是一个测试函数,将针对 TypedArray 中的每个元素执行。此函数接受名为 'element'、'index' 和 'array' 的三个参数。以下是每个参数的描述 -
- element − 表示 TypedArray 中正在处理的当前元素。
- index − 指示 TypedArray 中当前元素的索引(位置)。
- array − 指整个 TypedArray。
- thisArg (可选) − 这是一个可选参数,允许您在 callbackFn 中指定 this 的值。
返回值
此方法返回满足 testing 函数的最后一个元素的索引。如果没有元素满足 testing 函数,则返回 '−1'。
示例 1
如果元素满足 testing 函数,它将返回类型化数组中最后一个元素的索引。
在下面的示例中,我们使用 JavaScript TypedArray findLastIndex() 方法来检索满足提供的测试函数的最后一个元素的索引。我们创建一个名为 isEven() 的测试函数,检查偶数,并将其作为参数传递给此方法。
<html>
<head>
<title>JavaScript TypedArray findLastIndex() Method</title>
</head>
<body>
<script>
function isEven(element, index, array){
return element %2 == 0;
}
const T_array = new Uint8Array([10, 20, 30, 40, 50, 60, 70, 80, 81]);
document.write("Typed array: ", T_array);
//calling function
document.write("<br>The index of the last even number is: ", T_array.findLastIndex(isEven));
</script>
</body>
</html>
输出
上面的程序返回最后一个偶数的索引为 7。
The index of the last even number is: 7
示例 2
在 TypedArray 中查找最后一个闰年的索引。
在下面给定的示例中,我们创建了一个名为 isLeapYear() 的函数,该函数检查此类型化数组 [2002, 2004, 2005, 2006, 2007, 2014] 中的闰年,并将此函数作为参数传递给 findLastIndex() 方法,以检索满足测试函数的最后一个闰年。
<html>
<head>
<title>JavaScript TypedArray findLastIndex() Method</title>
</head>
<body>
<script>
function isLeapYear(element, index, arrar){
return ((element % 4 == 0) && (element % 400 == 0 || element % 100 !=0));
}
const T_array = new Int16Array([2002, 2004, 2005, 2006, 2007, 2012]);
document.write("Typed array: ", T_array);
//calling function
document.write("<br>The index of the last leap year in typed array is: ", T_array.findLastIndex(isLeapYear));
</script>
</body>
</html>
输出
执行上述程序后,它将返回类型化数组中最后一个闰年的索引为 −
The index of the last leap year in typed array is: 5
示例 3
如果没有元素满足 testing 函数,findLastIndex() 方法将返回 '-1'。
以下是 JavaScript TypedArray findLastIndex() 方法的另一个示例。我们创建一个名为 isNegative() 的函数来检查负数,并将其作为参数传递给此方法,以检索满足测试函数的最后一个元素的索引。
<html>
<head>
<title>JavaScript TypedArray findLastIndex() Method</title>
</head>
<body>
<script>
function isNegative(element, index, array){
return element < 0;
}
const T_array = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]);
document.write("Typed array: ", T_array);
//calling function
document.write("<br>The index of last negative element: ", T_array.findLastIndex(isNegative));
</script>
</body>
</html>
输出
执行上述程序后,将返回 '-1'。
The index of last negative element: -1