every()
方法检查数组中的所有元素是否都通过给定的测试函数。
示例
// function that checks whether
// the age is 18 or above
function checkAdult(age) {
return age >= 18;
}
const ageArray = [34, 23, 20, 26, 12];
//checks if all the array elements
// pass the checkAdult() function
let check = ageArray.every(checkAdult);
// Output: false
every() 语法
every()
方法的语法是
arr.every(callback(currentValue), thisArg)
这里,arr 是一个数组。
every() 参数
every()
方法接受
- callback() - 用于测试每个数组元素的函数。它接受
currentValue
- 从数组中传递的当前元素。
thisArg
(可选) - 在执行callback()
时用作 this 的值。默认为undefined
。
every()返回值
every()
方法返回
- true - 如果所有数组元素都通过给定的测试函数(
callback
返回真值)。 - false - 如果任何数组元素未能通过给定的测试函数。
注意事项:
every()
不会更改原始数组。every()
不会为 empty 数组执行callback()
函数。如果我们传递一个 empty 数组,它总是返回 true。
示例 1:检查数组元素是否为偶数
// function that checks whether all
// the array elements are even or not
function checkEven(num) {
return num%2 === 0;
}
// create an array of numbers
const numbers = [2, 4, 6, 7, 8];
// use the every() method along with
// checkEven() on the numbers array
let check = numbers.every(checkEven);
console.log(check)
// Output: false
在上面的示例中,我们创建了 checkEven()
函数,该函数检查给定的数字是否为偶数。
然后,我们在 numbers
数组上调用 every()
方法。由于数组中有一个奇数(7),我们得到 false
作为输出。
示例 2:JavaScript every() 与箭头函数
let numbers = [ 1 , 2 , 3 , 4 , 5];
// use arrow function with every()
let result = numbers.every(element => element < 6);
console.log(result);
// Output: true
在上面的示例中,我们创建了 numbers
数组。然后,我们在该数组上调用 every()
方法。
注意 every()
方法中的箭头函数 element=> element < 6
。此函数检查给定的数组元素是否小于 6。
由于 numbers
数组中的所有元素都小于 6,我们得到 true
作为输出。
另请阅读