1

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.

Abhi Dhadve
  • 13
  • 1
  • 4

3 Answers3

3

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!

Morgoth
  • 4,935
  • 8
  • 40
  • 66
Rakesh_Kumar
  • 1,442
  • 1
  • 14
  • 30
  • Thanks for your answer and it is working. But i am still confused with why Array.method() is not working as douglas crockford used this example to explain augmenting Array.prototype. – Abhi Dhadve Jan 12 '15 at 09:07
  • Array.method doesn't exist and didn't. – Ginden Jan 12 '15 at 09:12
  • 1
    @AbhiDhadve This link will clear your doubts.. http://stackoverflow.com/questions/3966936/method-method-in-crockfords-book-javascript-the-good-parts . Also if mine answer helped you, accept it as answer.. ;) – Rakesh_Kumar Jan 12 '15 at 10:20
  • 2
    Here is the actual solution that @Rakesh_Kumar provided. First we have to add it to Function.prototype . Function.prototype.method = function (name, func) { this.prototype[name] = func; return this; }; – Abhi Dhadve Jan 12 '15 at 10:32
-1

I am reading the book as well and I I think this does not work because before in the book he defined a method called method to avoid the use of Array.prototype.something, or Function.prototype something everytime you want to add methods to array, function or objects prototypes.

viery365
  • 935
  • 2
  • 12
  • 30
-1
Function.prototype.method = function(name, func) {
this.prototype[name] = func;
return this;
};

Append the above code at the beginning. I had the same problem. They have mentioned this in Preface. Check it out.... I hope it helps.... :)

R.A.
  • 1