JavaScript Glossary: Array .every() Method
Publikováno: 6.2.2019
Basics
The every
method checks that each element in an array passes a set test. This method will return true
if all the elements pass the set. Once an element tha...
Basics
The every
method checks that each element in an array passes a set test. This method will return true
if all the elements pass the set. Once an element that fails the test is found, the method returns false
.
let result = [10, 5, 20, 100].every(function(number){
return number < 150
})
console.log(result) // true
https://scotch.io/embed/gist/f792890d0a8ec4f3340d0e7dd27c6aa0
The every
method:
- Takes a callback function that implements a test
- Checks if all the elements pass the test
- Returns
true
ifevery
element passes the test. - Returns
false
an element fails test
Syntax
const isCorrect = array.every(callback[,thisArg])
2 Parameters
callbackFunction(function) The function that tests each of the elements of the array. The callback function is required and can take three parameters:
element
: This is the element currently being executed -required
.index
: The index of the current item -optional
.array
: The array that is currently being processed -optional
.
thisArg (this) (optional)
An argument passed to be used as the this
value in the callback
- optional
Returns a single boolean value
This method will return true
of every element in the array passes the test and if the array is empty. It returns false
if an element within the array fails the test.
Common Uses and Snippets
Test an array for a matching threshold
When expecting a boolean
return value after testing all the elements within an array.
https://scotch.io/embed/gist/8152e3ad8f6f952b14caad1e931b167f
Testing an array of Objects
.every()
method can be used to test all items in an array of objects using either the object keys.
https://scotch.io/embed/gist/e53b9e8963170a4212278361adbec150