在JavaScript中查找数组的最小/最大元素 [英] Find the min/max element of an Array in JavaScript

查看:102
本文介绍了在JavaScript中查找数组的最小/最大元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何轻松获取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 );

这篇关于在JavaScript中查找数组的最小/最大元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆