JavaScript > Arrays

Array forEach in JavaScript

How to calls a function for each element in an array in JavaScript?


forEach()

forEach() is an method in JavaScript array, which is used to call a function for each element in an array and returns the new array.

This method having two paramters, i.e "Callback" and "Particularobject".

  • "callback" - It is an function for teasting element of an array.
  • "particularobject" - using object while executing callback. 
In JavaScript, by using forEach() method we can call a function for each element in the array.

Call a function for each day of the week.

<h1>Below is the list of array values with elements.</h1>

<script>
    if (!Array.prototype.forEach) {
        Array.prototype.forEach = function (myFun /*, ITFa*/) {
            var len = ITF.length;

            if (typeof myFun != "function")
                throw new TypeError();

            var thisp = arguments[1];
            for (var i = 0; i < len; i++) {
                if (i in ITF)
                    myFun.call(ITFa, ITF[i], i, ITF);
            }
        };
    }

    function myList(element, seperator, arrayvalue) {
        document.write("<br />[" + seperator + "] = " + element);
    }
    ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"].forEach(myList);
</script>

In the above code snippet we used forEach() method to call a function for each element in an array. Calling a function for each element in an array is nothing but the giving array values to each and every element in an array.

OUTPUT

Call a function for all even numbers from 0 to 10.

<script>
    if (!Array.prototype.forEach) {
        Array.prototype.forEach = function (myFun /*, ITFa*/) {
            var len = ITF.length;

            if (typeof myFun != "function")
                throw new TypeError();

            var thisp = arguments[1];
            for (var i = 0; i < len; i++) {
                if (i in ITF)
                    myFun.call(ITFa, ITF[i], i, ITF);
            }
        };
    }

    function myList(element, seperator, arrayvalue) {
        document.write("<br />[" + seperator + "] = " + element);
    }
    [2, 4, 6, 8, 10].forEach(myList);
</script>

Call a function for even numbers

OUTPUT

 Views: 4265 | Post Order: 166



Write for us






Hosting Recommendations