我有问题添加一个数组的所有元素以及平均它们。我将如何做到这一点,并实现它与我目前的代码?元素的定义如下所示。

<script type="text/javascript">
//<![CDATA[

var i;
var elmt = new Array();

elmt[0] = "0";
elmt[1] = "1";
elmt[2] = "2";
elmt[3] = "3";
elmt[4] = "4";
elmt[5] = "7";
elmt[6] = "8";
elmt[7] = "9";
elmt[8] = "10";
elmt[9] = "11";

// Problem here
for (i = 9; i < 10; i++){
  document.write("The sum of all the elements is: " + /* Problem here */ + " The average of all the elements is: " + /* Problem here */ + "<br/>");
}   

//]]>
</script>

当前回答

我认为这可能是用for循环和函数计算平均值的直接解决方案。

var elmts = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];

function average(arr) {
    var total = 0;
    for (var i = 0; i < arr.length; i++) {
        total += arr[i];
    }
        console.log(Math.round(total/arr.length));
}

average(elmts);

其他回答

平均最短的一行

const avg = arr => arr.reduce((acc,v,i,a)=>(acc+v/a.length),0);

Sum的最短一行

const sum = arr => arr.reduce((a,b)=>a+b);

这里是一个快速添加到“数学”对象在javascript中添加一个“平均”命令!!

Math.average = function(input) {
  this.output = 0;
  for (this.i = 0; this.i < input.length; this.i++) {
    this.output+=Number(input[this.i]);
  }
  return this.output/input.length;
}

然后我有这个加法“数学”对象得到和!

Math.sum = function(input) {
  this.output = 0;
  for (this.i = 0; this.i < input.length; this.i++) {
    this.output+=Number(input[this.i]);
  }
  return this.output;
}

那么你要做的就是

alert(Math.sum([5,5,5])); //alerts “15”
alert(Math.average([10,0,5])); //alerts “5”

我把占位符数组只是传递在你的变量(输入如果他们是数字可以是一个字符串,因为它解析到一个数字!)

将for循环计数器设置为0....你得到了元素9,然后你就完成了。其他答案都是基础数学。使用一个变量来存储你的和(需要将字符串转换为整数),然后除以你的数组长度。

ES6

Const average = arr => arr。Reduce ((p, c) => p + c, 0) / arr.length; Const result = average([4,4,5,6,6]);/ / 5 console.log(结果);

这是你的一句台词:

var average = arr.reduce((sum,item,index,arr)=>index !== arr.length-1?sum+item:sum+item/arr.length,0)