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

<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

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

在这种情况下,我推荐D3。它是最易读的(并提供了2种不同的平均值)

let d3 = require('d3');
let array = [1,2,3,4];
let sum = d3.sum(array); //10
let mean = d3.mean(array); //2.5
let median = d3.median(array); 

HTML内容的平均值

使用jQuery或Javascript的querySelector,您可以直接访问格式化的数据…例子:

<p>Elements for an average: <span class="m">2</span>, <span class="m">4</span>,
   <span class="m">2</span>, <span class="m">3</span>.
</p>

因此,使用jQuery

var A = $('.m')
  .map(function(idx) { return  parseInt($(this).html()) })
  .get();
var AVG = A.reduce(function(a,b){return a+b}) / A5.length;

查看其他4种方法(!)来访问itens和平均它:http://jsfiddle.net/4fLWB/

在常绿浏览器上,你可以使用箭头函数 Avg = [1,2,3].reduce((a,b) => (a+b);

运行10万次,for循环方法和reduce方法之间的时间差可以忽略不计。

s=Date.now();for(i=0;i<100000;i++){ n=[1,2,3]; a=n.reduce((a,b) => (a+b)) / n.length }; console.log("100k reduce took " + (Date.now()-s) + "ms."); s=Date.now();for(i=0;i<100000;i++){n=[1,2,3]; nl=n.length; a=0; for(j=nl-1;j>0;j--){a=a+n[j];} a/nl }; console.log("100k for loop took " + (Date.now()-s) + "ms."); s=Date.now();for(i=0;i<1000000;i++){n=[1,2,3]; nl=n.length; a=0; for(j=nl-1;j>0;j--){a=a+n[j];} a/nl }; console.log("1M for loop took " + (Date.now()-s) + "ms."); s=Date.now();for(i=0;i<1000000;i++){ n=[1,2,3]; a=n.reduce((a,b) => (a+b)) / n.length }; console.log("1M reduce took " + (Date.now()-s) + "ms."); /* * RESULT on Chrome 51 * 100k reduce took 26ms. * 100k for loop took 35ms. * 10M for loop took 126ms. * 10M reduce took 209ms. */