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

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

当前回答

一般来说,平均使用一行程序减少是这样的

elements.reduce(function(sum, a,i,ar) { sum += a;  return i==ar.length-1?(ar.length==0?0:sum/ar.length):sum},0);

特别是被问到的问题

elements.reduce(function(sum, a,i,ar) { sum += parseFloat(a);  return i==ar.length-1?(ar.length==0?0:sum/ar.length):sum},0);

一个有效的版本是

elements.reduce(function(sum, a) { return sum + a },0)/(elements.length||1);

1分钟内理解Javascript数组缩减 http://www.airpair.com/javascript/javascript-array-reduce

正如gotofritz指出的数组。Reduce跳过未定义的值。 所以这里有一个解决方案:

(function average(arr){var finalstate=arr.reduce(function(state,a) { state.sum+=a;state.count+=1; return state },{sum:0,count:0}); return finalstate.sum/finalstate.count})([2,,,6])

其他回答

如果你需要平均值并且可以跳过计算和的要求,你可以通过调用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
Array.prototype.avg=function(fn){
    fn =fn || function(e,i){return e};
    return (this.map(fn).reduce(function(a,b){return parseFloat(a)+parseFloat(b)},0) / this.length ) ; 
};

然后:

[ 1 , 2 , 3].avg() ;  //-> OUT : 2

[{age:25},{age:26},{age:27}].avg(function(e){return e.age}); // OUT : 26

在阅读了其他选项之后,我将尝试为未来的观众创建一个更简单的版本,详细说明现有的代码,而不是创建一个更优雅的代码。首先,您将数字声明为字符串。除了.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}`
  );}

我正好有10个元素(像例子中一样),所以我这样做:

( elmt[0] + elmt[1] + elmt[2] + elmt[3] + elmt[4] +
  elmt[5] + elmt[6] + elmt[7] + elmt[8] + elmt[9] ) / 10

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

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