JavaScript TypeArray find() 方法返回当前类型化数组中满足提供的测试函数的第一个元素的值。如果未满足任何值或没有将任何值传递给 testing 函数,则返回 undefined。
以下是关于 find() 方法的一些附加要点 -
- find() 方法对 TypedArray(例如 Uint8Array、Int16Array 等)进行操作。
- 它接受 testing 函数作为参数。
- 对 TypedArray 中的每个元素执行 testing 函数。
- 如果元素满足 testing 函数指定的条件(返回 true 值),则该元素将作为结果返回。
- 如果没有元素传递给 testing 函数,则返回 undefined。
语法
以下是 JavaScript TypedArray find() 方法的语法 -
find(callbackFn, thisArg)
参数
此方法接受两个名为 'callbackFn' 和 'thisArg' 的参数,如下所述 -
- callbackFn − 此参数是一个测试函数,将针对 TypedArray 中的每个元素执行。此函数接受名为 'element'、'index' 和 'array' 的三个参数。以下是每个参数的描述 -
- element − 表示 TypedArray 中正在处理的当前元素。
- index − 指示 TypedArray 中当前元素的索引(位置)。
- array − 指整个 TypedArray。
- thisArg (可选) − 这是一个可选参数,允许您在 callbackFn 中指定 this 的值。
返回值
此方法返回满足提供的测试函数的第一个元素 TypedArray,否则返回 'undefined' 。
示例 1
在下面的示例中,我们使用 JavaScript TypedArray find() 方法搜索原始 TypedArray [1, 2, 3, 4, 5, 6, 7, 8] 中的第一个偶数。我们创建一个名为 isEven() 的测试函数来检查数字是否为偶数,然后将此函数作为参数传递给 find() 方法。
<html>
<head>
<title>JavaScript TypedArray find() Method</title>
</head>
<body>
<script>
function isEven(element, index, array){
return element %2 == 0;
}
const T_array = new Int8Array([1, 2, 3, 4, 5, 6, 7, 8]);
document.write("Orizinal TypedArray: ", T_array);
document.write("<br>First even number in TypedArray is: ");
document.write(T_array.find(isEven));
</script>
</body>
</html>
输出
上面的程序返回 TypedArray [1, 2, 3, ,4 ,5 ,6 ,7, 8] 中的第一个偶数作为 '2'
First even number in TypedArray is: 2
示例 2
以下是 JavaScript TypedArray find() 的另一个示例。我们使用此方法搜索此类型数组 [1, 2, -1, 0, 1, 2, -2, -3] 中的第一个负数。我们创建一个名为 isNegative() 的测试函数,用于检查数字是否为负数,然后将此函数作为参数传递给 find() 方法。
<html>
<head>
<title>JavaScript TypedArray find() Method</title>
</head>
<body>
<script>
function isNegative(element, index, array){
return element < 0;
}
const T_array = new Int8Array([1, 2, -1, 0, 1, 2, -2, -3]);
document.write("Orizinal TypedArray: ", T_array);
document.write("<br>First negative number in TypedArray is: ");
document.write(T_array.find(isNegative));
</script>
</body>
</html>
输出
执行上述程序后,返回 TypedArray [1, 2, -1, 0, 1, 2, -2, -3] 中的第一个负数 -1。
First negative number in TypedArray is: -1
示例 3
如果没有值满足 testing 函数,它将返回 'undefined'。
在这个程序中,我们创建了一个名为 isPrime() 的函数,用于检查一个数字是否是素数。我们使用此函数作为 find() 函数的参数来检索 TypedArray [4, 6, 8, 9] 中的第一个素数。但是,由于没有值满足 isPrime() 函数,因此 find() 方法返回 undefined。
<html>
<head>
<title>JavaScript TypedArray find() Method</title>
</head>
<body>
<script>
function isPrime(element, index, array){
let begin = 2;
while(begin <= Math.sqrt(element)){
if(element % begin++ < 1){
return false;
}
}
return element > 1;
}
const T_array = new Int8Array([4, 6, 8, 9]);
document.write("Orizinal TypedArray: ", T_array);
document.write("<br>First negative number in TypedArray is: ");
document.write(T_array.find(isPrime));
</script>
</body>
</html>
输出
一旦执行了上述程序,它将返回 'undefined'。
First negative number in TypedArray is: undefined