Hello reader's under this blog we are going to apply a function against each array element. We are using a function to check an array value and if it matches a given value then it will replaced.
To attach a callback function to each array element by using the new ECMAScript 5 Array object forEach:-
Syntax:-
var charSets = new Array("ab","bb","cd","ab","cc","ab","dd","ab");
function replaceElement(element,index,array) {
if (element == "ab") array[index] = "**";
}
// apply function to each array element
charSets.forEach(replaceElement);
alert(charSets); // prints **,bb,cd,**,cc,**,dd,**
The function parameter is taken by the forEach method. The function has three parameters the array element, index of the element and the array. All were used in the "replaceElement" function .
First value is tested to check whether it matches "ab" in a given string . Transformation of an array element’s value with the replacement string ** can be done by using the array element’s index in case if it matched.
Most modern browsers support forEach. if any of the browsers does not support you can use the Array.prototype property. a description is provided by Mozilla how to use forEach at https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Array/forEach.
Below is the forEach method for using the function :-
Syntax:-
if (!Array.prototype.forEach){
Array.prototype.forEach = function(fun /*, thisp*/){
var len = this.length >>> 0;
if (typeof fun != "function")
throw new TypeError();
var thisp = arguments[1];
for (var i = 0; i < len; i++){
if (i in this)
fun.call(thisp, this[i], i, this);
}
};
}
This tutorial will help you to understand the forEach method.
0 Comment(s)