JavaScript TypeArray every() 方法用于确定类型化数组中的所有元素是否都通过了给定的测试。此测试由名为 callbackFn 的函数实现。如果类型化数组中的所有元素都通过测试,则该方法返回布尔值 true。如果任何元素未通过测试,则该方法返回 false。
以下是您应该了解的有关 'every()' 方法的一些其他要点 -
- every() 方法对 TypedArray(例如 Uint8Array、Int16Array 等)进行操作。
- 它接受 testing 函数作为参数。
- 对 TypedArray 中的每个元素执行 testing 函数。
- 如果元素满足 testing 函数指定的条件(它返回 true 值)。
语法
以下是 JavaScript TypedArray every() 方法的语法 -
every(callbackFn, thisArg)
参数
此方法接受两个名为 'callbackFn' 和 'thisArg' 的参数,如下所述 -
- callbackFn − 此参数是一个测试函数,将针对 TypedArray 中的每个元素执行。此函数接受名为 'element'、'index' 和 'array' 的三个参数。以下是每个参数的描述 -
- element − 表示 TypedArray 中正在处理的当前元素。
- index − 指示 TypedArray 中当前元素的索引(位置)。
- array − 指整个 TypedArray。
- thisArg (可选) − 这是一个可选参数,允许您在 callbackFn 中指定 this 的值。
返回值
如果类型化数组中的所有元素都通过了回调函数实现的测试,则此方法返回 true,否则返回 false。
示例 1
如果类型化数组中的每个元素都未通过 callbackFn 测试,则返回 false。
在下面的示例中,我们使用 JavaScript TypedArray every() 方法来检查此类型化数组 [1, 2, 3, 4, 5, 6, 7, 8] 的所有元素是否都通过了名为 isEven() 的回调函数实现的测试。该函数检查偶数值或奇数值。
<html>
<head>
<title>JavaScript TypedArray every() 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("The typedArray elements are: ", T_array);
document.write("<br>Are all the elements in the typed array even? ", T_array.every(isEven));
</script>
</body>
</html>
输出
上述程序返回 'false'。
The typedArray elements are: 1,2,3,4,5,6,7,8
Are all the elements in the typed array even? false
Are all the elements in the typed array even? false
示例 2
如果类型化数组中的每个元素都通过 callbackFn 测试,则返回 true。
这是 JavaScript TypedArray every() 方法的另一个示例。我们使用此方法来检查类型化的 [−1, −2, −3, −4, −5, −6, −7, −8] 数组的所有元素是否都通过了名为 isNegative() 的函数提供的测试。该函数确定一个值是否为负数,我们将此函数作为参数传递给此方法。
<html>
<head>
<title>JavaScript TypedArray every() Method</title>
</head>
<body>
<script>
function isNegative(element, index, array){
return element < 0;
}
const T_array = new Int8Array([-1, -2, -3, -4, -5, -6, -7, -8]);
document.write("The typedArray elements are : ", T_array);
document.write("<br>Are all the elements in the typed array negative ? ", T_array.every(isNegative));
</script>
</body>
</html>
输出
执行上述程序后,返回 'true'。
The typedArray elements are : -1,-2,-3,-4,-5,-6,-7,-8
Are all the elements in the typed array negative ? true
Are all the elements in the typed array negative ? true