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

<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>

当前回答

你也可以使用lodash, _.sum(数组)和_.mean(数组)在数学部分(也有其他方便的东西)。

_.sum([4, 2, 8, 6]);
// => 20
_.mean([4, 2, 8, 6]);
// => 5

其他回答

我认为这可能是用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);

一种狡猾的方法可以做到这一点,尽管它确实需要使用(非常讨厌的)eval()。

var sum = eval(elmt.join('+')), avg = sum / elmt.length;
document.write("The sum of all the elements is: " + sum + " The average of all the elements is: " + avg + "<br/>");

我只是想把这个作为“盒子外”的选项之一。你永远不知道,狡猾可能会给你加分(或扣分)。

在阅读了其他选项之后,我将尝试为未来的观众创建一个更简单的版本,详细说明现有的代码,而不是创建一个更优雅的代码。首先,您将数字声明为字符串。除了.parseInt,我们还可以做:

const numberConverter = elmt.map(Number);

map所做的就是“返回原始数组的副本”。但是我把它的值转换成数字。然后我们可以使用reduce方法(它也可以更简单,但我写的是易于阅读的版本,我也有2个平均方法)reduce方法所做的是,它有一个累加器,当它遍历数组并添加(在这种情况下)currentValue时,如果你向它添加值,它会变得越来越大。

var i;
const 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';

console.log(elmt);

const numberConverter = elmt.map(Number);

const sum = numberConverter.reduce((accumulator, currentValue) => {
  return accumulator + currentValue;
}, 0);

const average = numberConverter.reduce(
  (accumulator, currentvalue, index, numArray) => {
    return accumulator + currentvalue / numArray.length;
  },
  0
);

const average2 =
  numberConverter.reduce(
    (accumulator, currentValue) => accumulator + currentValue,
    0
  ) / numberConverter.length;

for (i = 9; i < 10; i++) {
  console.log(
    `The sum of all the elements is: ${sum}. <br> The average of all the elements is: ${average2}`
  );}

我在我的个人库中使用这些方法:

Array.prototype.sum = Array.prototype.sum || function() {
  return this.reduce(function(sum, a) { return sum + Number(a) }, 0);
}

Array.prototype.average = Array.prototype.average || function() {
  return this.sum() / (this.length || 1);
}

编辑: 要使用它们,只需询问数组的和或平均值,如下所示:

[1,2,3].sum() // = 6
[1,2,3].average() // = 2

平均最短的一行

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

Sum的最短一行

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