Find the min/max element of an Array in JavaScript

前端 未结 30 2057
無奈伤痛
無奈伤痛 2020-11-21 06:18

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

Example Psuedocode:

let array = [100, 0, 50]

array.min() //=> 0
array.max()         


        
30条回答
  •  余生分开走
    2020-11-21 06:47

    ChaosPandion's solution works if you're using protoype. If not, consider this:

    Array.max = function( array ){
        return Math.max.apply( Math, array );
    };
    
    Array.min = function( array ){
        return Math.min.apply( Math, array );
    };
    

    The above will return NaN if an array value is not an integer so you should build some functionality to avoid that. Otherwise this will work.

提交回复
热议问题