Saturday 15 September 2018

JavaScript: Array: forEach: Apply function on every element of the array

‘forEach’ function is used to apply function on every element of the array.

Syntax
arr.forEach(callback[, thisArg])

callback is a function that takes following three arguments.
Argument
Description
currentValue
The current element being processed in the array.
index
The index of the current element being processed in the array.
array
The array that forEach() is being applied to.

thisArg
Optional. Value to use as this when executing callback.

Find sum of elements in array
var sum = 0;
arr1.forEach(function(value){
         sum += value;
})

Square every element of the array
arr1.forEach(function(value, index, arr1){
         arr1[index] = value * value;
});

Print every element in the array
arr1.forEach(function(value){
         document.write(value + "<br />");
});

forEach.html

<!DOCTYPE html>

<html>

<head>
    <title>Array forEach</title>
</head>

<body>
    <script type="text/javascript">
        var arr1 = [2, 3, 5, 7];

        var sum = 0;
        arr1.forEach(function(value) {
            sum += value;
        })

        document.write("Sum of elements in arr1 is " + sum + "<br />");

        /* Square every elements of the array */
        arr1.forEach(function(value, index, arr1) {
            arr1[index] = value * value;
        });

        /* Display elements in array */
        document.write("<br />Elements in arr1 are <br />");
        arr1.forEach(function(value) {
            document.write(value + "<br />");
        });
    </script>
</body>

</html>

Open above page in browser, you can able to see following text.

Sum of elements in arr1 is 17

Elements in arr1 are
4
9
25
49


If the array is sparse, the function you pass is not invoked for nonexistent elements.     


Previous                                                 Next                                                 Home

No comments:

Post a Comment