Math.min.apply(0, array) - why?

后端 未结 4 1170
情话喂你
情话喂你 2020-12-13 13:31

I was just digging through some JavaScript code (Raphaël.js) and came across the following line (translated slightly):

Math.min.apply(0, x)

4条回答
  •  忘掉有多难
    2020-12-13 13:59

    I realized the answer as I was posting my own question: This is the most succinct way of taking the min of an array x in JavaScript. The first argument is totally arbitrary; I find the 0 confusing because the code intuitively means "Take the min of 0 and x," which is absolutely not the case. Using the Math object makes more sense for human-readability, but the Raphael.js authors are obsessed with minification and 0 is three bytes shorter.

    See http://ejohn.org/blog/fast-javascript-maxmin/

    For readability's sake, I'd strongly urge people to stop doing this and instead define a function along the lines of

    function arrayMin(arr) { return Math.min.apply(Math, arr); };
    

提交回复
热议问题