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
373 views
in Technique[技术] by (71.8m points)

javascript - 在JavaScript中找到数组的最小/最大元素(Find the min/max element of an Array in JavaScript)

How can I easily obtain the min or max element of a JavaScript Array?

(如何轻松获得JavaScript数组的min或max元素?)

Example Psuedocode:

(伪代码示例:)

let array = [100, 0, 50]

array.min() //=> 0
array.max() //=> 100
  ask by HankH translate from so

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

1 Reply

0 votes
by (71.8m points)

How about augmenting the built-in Array object to use Math.max / Math.min instead:

(如何扩充内置Array对象以使用Math.max / Math.min代替:)

Array.prototype.max = function() {
  return Math.max.apply(null, this);
};

Array.prototype.min = function() {
  return Math.min.apply(null, this);
};

Here is a JSFiddle .

(这是一个JSFiddle 。)

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:

(增强内置函数可能会导致与其他库的冲突(有些人看到了),因此您可以更轻松地将直接apply 'ing Math.xxx()直接应用于数组:)

var min = Math.min.apply(null, arr),
    max = Math.max.apply(null, arr);

Alternately, assuming your browser supports ECMAScript 6, you can use the spread operator which functions similarly to the apply method:

(或者,假设您的浏览器支持ECMAScript 6,则可以使用散布运算符 ,其功能类似于apply方法:)

var min = Math.min( ...arr ),
    max = Math.max( ...arr );

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

...