-1

我已经阅读了有关 for-of 循​​环的其他问题,并提出了此代码计算数组中所有元素的平均值和总和,似乎有一些不正确的地方,将不胜感激。:

var i;
elmt=[]
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;

var sum = 0;
for (let sum of elmt) {
    sum += parseInt( elmt[i], 10 ); 
}
var avg = sum/elmt.length;

document.write( "The sum of all the elements is: " + sum + " The average is: " + avg );
<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Loops</h2>

<p id="demo"></p>

</body>
</html>

如果你们知道使用“for-of”循环做同样事情的其他更简单的方法,请随时分享。

4

3 回答 3

1

您正在使用两种循环。您可以选择普通的 for循环或for...of循环:

// For loop
for (i = 0; i < elms.length; i++) { 
  sum += elmt[i];
}

// For...of loop
for (let e of elmt) { 
  sum += e;
}

但是,更简洁的方法是使用reduce

var sum = elms.reduce((a, c) => a + c, 0);
var avg = sum / elms.length;
于 2019-01-19T14:40:17.547 回答
0

尝试以下

var elmt = [0,1,2,3,4,7,8,9,10,11];

//Using reduce()

function totalReduce(arr) {
  if(!Array.isArray(arr)) return;
  return arr.reduce((a, v)=>a + v);
}

//Using for loop

function totalForLoop(arr) {
  if(!Array.isArray(arr)) return;
  let totalNumber = 0;
  for (let i=0,l=arr.length; i<l; i++) {
     totalNumber+=arr[i];
  }
  return totalNumber;
}
// Using while loop

function totalWhile(arr) {
  if(!Array.isArray(arr)) return;
  let totalNumber = 0, i=-1;
  while (++i < arr.length) {
     totalNumber+=arr[i];
  }
  return totalNumber;
}
// Using array forEach

function totalForEach(arr) {
  if(!Array.isArray(arr)) return;
  let sum=0;
  arr.forEach(each => {
    sum+=each;
  });
  return sum;
};


var sum = totalReduce(elmt);

console.log( "Sum Using reduce: " + sum + " Average: " + sum/elmt.length );

sum = totalForLoop(elmt);
console.log( "Sum Using totalForLoop: " + sum + " Average: " + sum/elmt.length );

sum = totalWhile(elmt);
console.log( "Sum Using totalWhile: " + sum + " Average: " + sum/elmt.length );

sum = totalForEach(elmt);
console.log( "Sum Using totalForEach: " + sum + " Average: " + sum/elmt.length );

reduce()方法在数组的每个成员上执行一个 reducer 函数(您提供),从而产生一个输出值。

于 2019-01-19T14:47:26.580 回答
0
<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Loops</h2>

<p id="demo"></p>

<script>
var i;
elmt=[]
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;

var sum = 0;
for (let x of elmt) {
    sum += x;
}
var avg = sum/elmt.length;

document.write( "The sum of all the elements is: " + sum + " The average is: " + avg );
</script>

</body>
</html>

假设所有元素都是数字,否则您需要进行类型检查以忽略 NaN 条目。

于 2019-01-19T14:48:09.200 回答