0

hello im trying to build this function into my code:

Array.max = function (array) {
    return Math.max.apply(Math, array);
};

Array.min = function (array) {
    return Math.min.apply(Math, array);
};

as dictated by: JavaScript: min & max Array values?. However when i try to call it using:

console.log(a.max());

where

a = [245, 3, 40, 89, 736, 19, 138, 240, 42]

I get the following Error:

Uncaught TypeError: Object [object Array] has no method 'max' 

Can someone help me with this?

Community
  • 1
  • 1
toy
  • 422
  • 1
  • 7
  • 19
  • possible duplicate of [JavaScript: min & max Array values?](http://stackoverflow.com/questions/1669190/javascript-min-max-array-values) – thefourtheye Jan 02 '14 at 05:45
  • this is not a duplicate especially since i obviously referenced the post! this was more of an issue of js prototype programming not how to prototype are particular func – toy Jan 02 '14 at 20:01

1 Answers1

5

You have to add those functions in the prototype, not on the Array object itself.

Array.prototype.max = function () {
...

Array.prototype.min = function () {
...

Apart from that, to make your program work, you have to make the following changes

Array.prototype.max = function () {
    return Math.max.apply(null, this);
};

Array.prototype.min = function() {
    return Math.min.apply(null, this);
};

You want to call those functions on the current Array object, so, you have to use this variable instead of accepting an array as a parameter.

thefourtheye
  • 233,700
  • 52
  • 457
  • 497
  • thx - i clearly picked the wrong answer. still new to the whole 'prototype' concept as opposed to just adding methods – toy Jan 02 '14 at 20:04