用 JavaScript 计算数组的平均值


以下是在 JavaScript 中计算数组平均值的代码 -

示例

 在线示例

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
   .result,
   .sample {
      font-size: 18px;
      font-weight: 500;
      color: blueviolet;
   }
   .sample {
      color: red;
   }
</style>
</head>
<body>
<h1>Calculating average of an array</h1>
<div><pre class="sample"></pre></div>
<div class="result"></div>
<button class="Btn">Check</button>
<h3>Click on the above button to see document state</h3>
<script>
   let resEle = document.querySelector(".result");
   let BtnEle = document.querySelector(".Btn");
   let sampleEle = document.querySelector(".sample");
   let arr = [1, 2, 3, 4, 5, 11, 22];
   sampleEle.innerHTML = arr;
   BtnEle.addEventListener("click", () => {
      let sum = 0;
      arr.forEach((item) => (sum += item));
      resEle.innerHTML = "The average of the array = " + sum / arr.length;
   });
</script>
</body>
</html>

输出

单击“计算”按钮时 -


更新于:17-Jul-2020

461 次浏览

启动你的 职业

通过完成课程获得认证

开始吧
广告