Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
344 views
in Technique[技术] by (71.8m points)

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

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

Math.min.apply(0, x)

where x is an array. Why on earth would you do this? The behavior seems to be "take the min from the array x."

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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); };

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...