On Sun, Jul 17, 2011 at 10:23 PM, Matthew Bramer <[email protected]> wrote: > I think after reading everyone's thoughts on this topic, I probably could > *get* the higher level stuff or at least have a great reference to look at. > > @Peter, > Could you provide some use cases for .apply()? I really appreciate it!
A simple case is getting the max value for an array of numbers. Math.max is a function that returns the highest number out of all those passed on. The thing is, Math.max does not accept an array to walk through them, only number parameters. So you can do Math.max(1,2) and it returns 2. However, it does accept a dynamic number of arguments. So Math.max(1,2,3) returns 3. Math.max(1,2,3,2,5,3,1,0) returns 5, and so forth. Now say we have an array with some random numbers (say, the scores for some exam). We can now use apply to map this array as individual parameters onto Math.max and get the highest number from the array back: var arr = [1,2,3,2,5,3,1,0]; var max = Math.max.apply(null, arr); // max = 5 There is no other way of doing this kind of trick. - peter -- To view archived discussions from the original JSMentors Mailman list: http://www.mail-archive.com/[email protected]/ To search via a non-Google archive, visit here: http://www.mail-archive.com/[email protected]/ To unsubscribe from this group, send email to [email protected]
