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

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

当前回答

我认为一个更优雅的解决方案:

const sum = times.reduce((a, b) => a + b, 0);
const avg = (sum / times.length) || 0;

console.log(`The sum is: ${sum}. The average is: ${avg}.`);

其他回答

只是为了好玩:

var elmt = [0, 1, 2,3, 4, 7, 8, 9, 10, 11], l = elmt.length, i = -1, sum = 0;
for (; ++i < l; sum += elmt[i])
    ;
document.body.appendChild(document.createTextNode('The sum of all the elements is: ' + sum + ' The average of all the elements is: ' + (sum / l)));

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

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

我认为一个更优雅的解决方案:

const sum = times.reduce((a, b) => a + b, 0);
const avg = (sum / times.length) || 0;

console.log(`The sum is: ${sum}. The average is: ${avg}.`);

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

只是为了好玩

让avg =[81、77、-88、195、6.8].reduce ((a, e, i) = >(*我+ e) / (i + 1)); console.log (avg)