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.

0

3 Answers 3

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!

Sign up to request clarification or add additional context in comments.

4 Comments

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.
Array.method doesn't exist and didn't.
@AbhiDhadve This link will clear your doubts.. stackoverflow.com/questions/3966936/… . Also if mine answer helped you, accept it as answer.. ;)
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; };
-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.

Comments

-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.... :)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.