如何轻松获取JavaScript数组的最小或最大元素?
How can I easily obtain the min or max element of a JavaScript Array?
示例Psuedocode:
Example Psuedocode:
let array = [100, 0, 50] array.min() //=> 0 array.max() //=> 100推荐答案
如何将内置的Array对象扩充到使用 Math.max / Math.min 而不是:
How about augmenting the built-in Array object to use Math.max/Math.min instead:
Array.prototype.max = function() { return Math.max.apply(null, this); }; Array.prototype.min = function() { return Math.min.apply(null, this); };这是 JSFiddle 。
Here is a JSFiddle.
增加内置插件会导致与其他库发生冲突(有些人看到),所以你可以更轻松地直接将'ing Math.xxx()添加到你的数组中:
Augmenting the built-ins can cause collisions with other libraries (some see), so you may be more comfortable with just apply'ing Math.xxx() to your array directly:
var min = Math.min.apply(null, arr), max = Math.max.apply(null, arr);
或者,假设您的浏览器支持ECMAScript 6,可以使用传播运营商,其功能类似于 apply 方法:
Alternately, assuming your browser supports ECMAScript 6, you can use the spread operator which functions similarly to the apply method:
var min = Math.min( ...arr ), max = Math.max( ...arr );