I am trying add a method to Array prototype.But it is giving me an error TypeError: Array.method is not a function
I am trying this example from JavaScript: The Good Parts.
Here is a piece of my code.
Array.method('reduce',function(f,value){
var i;
for(i=0; i < this.length; i+1){
value = f(this[i],value);
}
return value;
});
var data = [1,3,2,4,5,6,7,8,9];
var add = function(value1, value2){
return value1 + value2;
}
var result = data.reduce(add, 0);
console.log(result);
I want to apply the reduce method to data array. So i can do addition ,multiplication on array and return the result.
Most of the code you have tried is correct. I think you are trying to add all the elements and return using reduce function to array. But to achieve what you wanted,checkout fiddle link:
http://jsfiddle.net/x2ydm091/2/
Array.prototype.reduce=function(f, value){
for(var i=0;i< this.length;i++){
value=f(this[i],value);
}
return value;
};
var add = function(a,b){
return a+b;
}
var data = [1,3,2,4,5,6,7,8,9];
var result = data.reduce(add,0);
alert(result);
Hope that helps!