JavaScript Array method: forEach()
[this page | pdf | back links]
The forEach() method (when applied to a JavaScript
array) calls
a function for each element of an array that has a value.
It
has the following syntax with the following parameters. Its return value is
undefined.
array.forEach(function(currentValue,
index, arr), thisValue)
Parameter
|
Required / Optional
|
Description
|
function(currentValue,
index, arr)
|
Required
|
A function to be run
for each element
|
thisValue
|
Optional
|
A value to be passed to
the function to be used as its ‘this’ value (if empty then thisValue
will be undefined)
|
The function
arguments are:
Parameter
|
Required / Optional
|
Description
|
currentValue
|
Required
|
The value of the
current element
|
Index
|
Optional
|
The array index of the
current element
|
arr
|
Optional
|
The array object which
the current element belongs to
|
EXAMPLE:
HTML USED IN THIS EXAMPLE:
<!DOCTYPE html>
<html> <!-- Copyright (c) Nematrian Limited 2018 -->
<head>
<style>
table,th,tr,td {border: 1px solid black; border-collapse: collapse;}
</style>
</head>
<body>
<table>
<tr>
<th>Example</th>
<th>Resulting value of <code>x</code></th>
</tr>
<tr>
<td><code id="Example"></code></td>
<td><code id="Result"></code></td>
</tr>
</table>
<script>
var x = 0;
var h = [-1, 2, 3];
h.forEach(sumsquare);
document.getElementById("Example").innerHTML =
'var s = 0;<br>var h = [-1, 2, 3];<br>' +
'function sumsquare(y) {<br>' +
' x = x + y * y;<br>' +
'}<br>' +
'h.forEach(sumsquare);';
document.getElementById("Result").innerHTML = x;
function sumsquare(y) {
x = x + y * y;
}
</script>
</body>
</html>
|
FUNCTION THAT MAY ASSIST IN TESTING WHETHER FEATURE IS SUPPORTED:
function isSupportedJavaScriptMethodArrayForEach() {
var h = [1, 2, 3]; return !!h.forEach;
} |
NAVIGATION LINKS
Contents | Prev | Next | JavaScript Arrays