The array method is often asked in interviews, which is summarized here
- Array.every()
The every() method is used to check whether all elements of an array meet the specified criteria (provided by the function).
var ages = [32.33.16.40];
function checkAdult(age) {
return age >= 18;
}
(function myFunction() {
console.log(ages.every(checkAdult)); }) ()Copy the code
- Array.some()
The //some() method checks if there are elements in an array that match the specified criteria (provided by a function).
var ages = [32.33.16.40];
function checkAdult(age) {
return age >= 18;
}
function myFunction() {
console.log(ages.some(checkAdult));
}
Copy the code
- Array.forEach()
The forEach() method is used to call each element of the array and pass the element to the callback function.
var numbers = [4.9.16.25];
function myFunction(item, index) {
console.log(index,item);
}
numbers.forEach(myFunction)
Copy the code
- Array.filter()
// Filter all elements in an array to return a new array
var ages = [32.33.16.40];
function checkAdult(age) {
return age >= 18;
}
(function myFunction() {
console.log(ages.filter(checkAdult)); }) ()Copy the code