Javascript最大最小平均

时间:2019-09-07 02:05:00

标签: javascript

我正在寻找此代码的最大,最小,平均数,其预期输出为[10,-2,3.5]

function MaxMinAvg (arr){

    var max = arr[0]
    var min = arr[0]
    var sum = arr[0]

    for (var i = 1; i < arr.length; i++){

    if (arr[i] > max){
    max = arr[i]
    }
    if (arr[i] < min){
    min = arr[i];
    }
    sum = sum + arr[i];
    var avg = arr[i] / arr.length;
    var arr2 = [max, min, avg];
    }
    return arr2;
    }
[10,-2,3.5]

1 个答案:

答案 0 :(得分:1)

您的代码几乎是正确的,但是您需要将avg计算和最终数组创建移至for循环 。而且,平均值就是总和除以总单位。

const maxMinAvg = arr => {

    let max = arr[0];
    let min = arr[0];
    let sum = arr[0];
    
    for (var i = 1; i < arr.length; i++){

      if (arr[i] > max){
        max = arr[i]
      }

      if (arr[i] < min){
        min = arr[i];
      }

      sum = sum + arr[i];
    }

    return [max, min, sum / arr.length];;
};

console.log(maxMinAvg([1, 5, 10, -2])); 

使用array :: reduce:

稍微精简的版本

const maxMinAvg = arr => {
    const [max, min, sum] = arr.reduce(([max, min, sum], current) => {
      if (max < current) max = current;
      if (min > current) min = current;
      sum += current;

      return [max, min, sum];
    }, [arr[0], arr[0], arr[0]]);

    return [max, min, sum / arr.length];;
};

console.log(maxMinAvg([1, 5, 10, -2]));