Javascript Array getMax()

Description

Javascript Array getMax()


/**/*from w ww .  j  a v  a  2  s.  c  o m*/
 * 
 */
Array.prototype.getMax = function() {
  var max = this[0];
  for (var x = 1; x < this.length; x++) {
    if (this[x] > max) {
      max = this[x];
    }
  }
  return max;
};

Javascript Array getMax()

Array.prototype.getMax = function() {
    let max = Math.max(...this);
    return max;/*ww  w .java  2s  .  co m*/
}

//adding a method to arrays to sum their number elements
Array.prototype.sum = function() {
    let sum = this.reduce((prev, curr) => prev + curr)
    return sum;
}

let numbers = [9, 1, 11, 3, 4];
let max = numbers.getMax();
console.log(`[${numbers.join(', ')}].getMax() = ${max}`);

console.log(`[${numbers.join(', ')}].sum() = ${numbers.sum()}`);

Javascript Array getMax()

Array.prototype.getMax = function getMax() {

    var temp = 0;
    for (var x = 1; x < this.length; x++) {
        if (this[x] > this[temp]) {
            temp = x;// w  ww .ja  va2 s  .  com
        }
    }
    return this[temp];
}



PreviousNext

Related