Java Reference
In-Depth Information
Evaluating Predicates
You can check if a predicate evaluates to true for all or some of the elements in an array.
The following two methods let you perform this:
every(predicate, thisArg)
some(predicate, thisArg)
The first argument, predicate , is a function that is called once for every existing
elements in the array. The function is passed three arguments: the value of the element,
the index of the element, and the array object. The second argument, thisArg , if
specified, is used as the this value for the function invocation specified by predicate .
The every() method returns true if the specified predicate function returns a
truthy value for every existing elements in the array. Otherwise, it returns false . The
method returns false as soon as predicate returns a falsy value for an element.
The some() method returns true if predicate returns a truthy value for at least one
element. Otherwise, it returns false . The method returns true as soon as predicate
returns a truthy value for an element. The following example shows how to check if an
array of numbers contains any/all even/odd numbers:
var ids = [10, 20, 30, 20];
print("ids = " + ids);
var hasAnyEven = ids.some(function (value, index, array) {
return value %2 === 0;
});
var hasAllEven = ids.every(function (value, index, array) {
return value %2 === 0;
});
var hasAnyOdd = ids.some(function (value, index, array) {
return value %2 === 1;
});
var hasAllOdd = ids.every(function (value, index, array) {
return value %2 === 1;
});
print("ids has any even numbers: " + hasAnyEven);
print("ids has all even numbers: " + hasAllEven);
print("ids has any odd numbers: " + hasAnyOdd);
print("ids has all odd numbers: " + hasAllOdd);
ids = 10,20,30,20
ids has any even numbers: true
ids has all even numbers: true
ids has any odd numbers: false
ids has all odd numbers: false
 
Search WWH ::




Custom Search