Find the min/max element of an Array in JavaScript

前端 未结 30 2124
無奈伤痛
無奈伤痛 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:42

    Simple stuff, really.

    var arr = [10,20,30,40];
    arr.max = function() { return  Math.max.apply(Math, this); }; //attach max funct
    arr.min = function() { return  Math.min.apply(Math, this); }; //attach min funct
    
    alert("min: " + arr.min() + " max: " + arr.max());
    

提交回复
热议问题