最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

在JavaScript中查找数组的最小最大元素

SEO心得admin55浏览0评论
本文介绍了在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 );
发布评论

评论列表(0)

  1. 暂无评论