JavaScript - Arrays - every
// JavaScript - Array.prototype.every():
The every() method tests whether all elements in the array pass the test
implemented by the provided function.
arr.every(callback[, thisArg])
function isBigEnough(element, index, array) {
return element >= 10;
}
[12, 5, 8, 130, 44].every(isBigEnough); // false
[12, 54, 18, 130, 44].every(isBigEnough); // true
callback: Function to test for each element, taking three arguments:
1. currentValue (required): The current element being processed in the array.
2. index (optional): The index of the current element being processed in the array.
3. array (optional): The array every was called upon.
thisArgs: Optional. Value to use as this when executing callback.
The every() method returns true if the callback function returns a truthy
value for every array element; otherwise, false.
The every method executes the provided callback function once for each element
present in the array until it finds one where callback returns a falsy value
(a value that becomes false when converted to a Boolean). If such an element is
found, the every method immediately returns false. Otherwise, if callback
returned a true value for all elements, every will return true. callback is
invoked only for indexes of the array which have assigned values; it is not
invoked for indexes which have been deleted or which have never been assigned
values.
The callback is invoked with three arguments: the value of the element, the index
of the element, and the Array object being traversed.
The every method does not mutate the array on which it is called.
The range of elements processed by every is set before the first invocation of
callback. Elements which are appended to the array after the call to every
begins will not be visited by callback. If existing elements of the array are
changed, their value as passed to callback will be the value at the time every
visits them; elements that are deleted are not visited.
every acts like the "for all" quantifier in mathematics. In particular, for an
empty array, it returns true. (It is vacuously true that all elements of the
empty set satisfy any given condition.)
// Testing size of all array elements:
function isBigEnough(element, index, array) {
return element >= 10;
}
[12, 5, 8, 130, 44].every(isBigEnough); // false
[12, 54, 18, 130, 44].every(isBigEnough); // true
// Using arrow functons.
// Arrow functions provide a shorter syntax for the same test.
[12, 5, 8, 130, 44].every(elem => elem >= 10); // false
[12, 54, 18, 130, 44].every(elem => elem >= 10); // true
The every method was added to the ECMA-262 standard in the 5th edition.
page revision: 1, last edited: 14 Nov 2016 20:29