Java Reference
In-Depth Information
The first line of code creates an array called
colors
. It has four elements (two of which are
blue
). The
second line alerts
0
to the user, because
red
is the first element of the array. The third line returns the
value of
3
because the
lastIndexOf()
method begins its search at the very end of the array.
Both the
indexOf()
and
lastIndexOf()
methods return
‐1
if the provided value cannot be found in
the array.
Iterating through an Array without Loops
The remaining five methods are called iterative methods because they iterate, or loop, through the
array. In addition, these methods execute a function that you define on every element while they
iterate through the array. The function these methods use must follow one rule—it must accept
three arguments like the following code:
function functionName(value, index, array) {
// do something here
}
When executed, JavaScript passes three arguments to your function. The first is the value of
the element, the second is the index of the element, and the third is the array itself. These three
parameters enable you to perform just about any operation or comparison you might need in
relation to the array and its elements.
Testing Each Element—The every(), some(), and filter() Methods
Let's look at the
every()
and
some()
methods first. These are testing methods. The
every()
method
tests whether all elements in the array pass the test in your function. Consider the following code:
var numbers = [ 1, 2, 3, 4, 5 ];
function isLessThan3(value, index, array) {
var returnValue = false;
if (value < 3) {
returnValue = true;
}
return returnValue;
}
alert(numbers.every(isLessThan3));
The first line shows the creation of an array called
numbers
; its elements hold the values
1
through
5
. The next line defines the
isLessThan3()
function. It accepts the three mandatory arguments and
determines if the value of each element is less than
3
. The last line alerts the outcome of the
every()
test. Because not every value in the array is less than
3
, the result of the
every()
test is
false
.
Contrast this with the
some()
method. Unlike
every()
, the
some()
test only cares if some of the
elements pass the test in your function. Using the same
numbers
array and
isLessThan3()
function,
consider this line of code:
alert(numbers.some(isLessThan3));