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

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

当前回答

如果你需要平均值并且可以跳过计算和的要求,你可以通过调用reduce来计算平均值:

// Assumes an array with only values that can be parsed to a Float
var reducer = function(cumulativeAverage, currentValue, currentIndex) {
  // 1. multiply average by currentIndex to find cumulative sum of previous elements
  // 2. add currentValue to get cumulative sum, including current element
  // 3. divide by total number of elements, including current element (zero-based index + 1)
  return (cumulativeAverage * currentIndex + parseFloat(currentValue))/(currentIndex + 1)
}
console.log([1, 2, 3, 4, 5, 6, 7, 8, 9, 10].reduce(reducer, 0)); // => 5.5
console.log([].reduce(reducer, 0)); // => 0
console.log([0].reduce(reducer, 0)); // => 0
console.log([].reduce(reducer, 0)); // => 0
console.log([,,,].reduce(reducer, 0)); // => 0
console.log([].reduce(reducer, 0)); // => 0

其他回答

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

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

这是你的一句台词:

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

首先定义我们计划使用的所有变量。您将注意到,对于数字数组,我使用了[]的文字符号,而不是构造函数方法array()。此外,我使用了一个更短的方法来将多个变量设置为0。

var numbers = [], count = sum = avg = 0;

接下来,我用0到11的值填充空数字数组。这是为了回到最初的起点。注意我是如何推入数组count++的。这将推动count的当前值,然后在下一次增加该值。

while ( count < 12 )
    numbers.push( count++ );

最后,我为数字数组中的每个数字执行一个函数。这个函数一次处理一个数字,我在函数体中将其标识为“n”。

numbers.forEach(function(n){
  sum += n; 
  avg = sum / numbers.length;
});

最后,我们可以将sum值和avg值输出到控制台,以便查看结果:

// Sum: 66, Avg: 5.5
console.log( 'Sum: ' + sum + ', Avg: ' + avg );

在http://jsbin.com/unukoj/3/edit上看到它的行动

在支持es6的浏览器中,这个填充可能会有帮助。

Math.sum = (...a) => Array.prototype.reduce.call(a,(a,b) => a+b)

Math.avg = (...a) => Math.sum(...a)/a.length;

你可以在Math.sum和Math.sum之间共享相同的调用方法。avg和Math。马克斯,如

var maxOne = Math.max(1,2,3,4) // 4;

你可以用数学。总和为

var sumNum = Math.sum(1,2,3,4) // 10

或者如果你有一个数组要求和,你可以使用

var sumNum = Math.sum.apply(null,[1,2,3,4]) // 10

就像

var maxOne = Math.max.apply(null,[1,2,3,4]) // 4

一种狡猾的方法可以做到这一点,尽管它确实需要使用(非常讨厌的)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/>");

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