SitePoint Sponsor

User Tag List

Results 1 to 4 of 4

Thread: apply???

  1. #1
    SitePoint Evangelist
    Join Date
    Mar 2011
    Location
    Bellingham, WA
    Posts
    450
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)

    apply???

    Hello!

    I found the following code to be used to find the maximum of an array of values. I understand the concept of the array object in addition to Math.max but this is the first time that I've seen "apply" and I'm not sure how this particular code does what it does. If someone wouldn't mind giving me a quick explanation, I'd appreciate it.

    Code:
    Array.max = function( array ){
        return Math.max.apply( Math, array );
    };
    Thanks so much,

    Eric

  2. #2
    SitePoint Guru
    Join Date
    Apr 2006
    Posts
    802
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Math.max expects any number of number arguments, and returns the largest number of those arguments.

    Math.max(1,2,3) returns 3.

    If you passed it an array of numbers (Math.max([1,2,3]) it would return NaN, since an array is not a number.

    Calling Math.max.apply(Math,[1,2,3]) calls Math.max with the array passed as its arguments, just like Math.max(1,2,3).

  3. #3
    SitePoint Enthusiast Anthony.Barnes's Avatar
    Join Date
    Aug 2011
    Location
    Canberra, Australia
    Posts
    80
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I find examples the easiest to learn from:

    http://jsfiddle.net/FAUq4/2/

    .apply() is especially useful for functions that can take multiple arguments (like Math.max). It's also useful in that it can accept a context as it's first argument which will scope the functions 'this' variable, and the arguments can be programmatic-ally altered without changing the implementation of the function.

  4. #4
    SitePoint Evangelist
    Join Date
    Mar 2011
    Location
    Bellingham, WA
    Posts
    450
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    Thanks for the help!

    -Eric


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •