代码改变世界

Fast JavaScript Max/Min

2012-10-27 02:00  youxin  阅读(291)  评论(0)    收藏  举报

via:john resig http://ejohn.org/blog/fast-javascript-maxmin/

I've been saving this technique for a while now - it's simple, but it's good. What's the fastest way to find the largest, or smallest, number in an array?

There's a bunch of implementations floating around - including some nicely object-oriented approaches in Prototype. However, none of them can compare to the raw simplicity of this:

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

 

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

The premise behind this technique is simple (and obvious once you see it): Just find any built-in JavaScript function that takes unlimited arguments - it'll now be just as easy to adapt it for Array-wide use. By using JavaScript's .apply() method on a built-in function you can pass in an array of unlimited arguments.

After "discovering" this for myself I found out that it's mentioned in the "Rhino" book, which made me feel stupid. Oh well, it's a great trick and its one that more people should know.