Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

คำนวณค่าเฉลี่ย (Average) ของอาร์เรย์ใน JavaScript


ค่าเฉลี่ยเลขคณิต (Arithmetic Mean) คำนวณได้จากผลรวมของทุกค่า หารด้วยจำนวนสมาชิก สูตร: mean = sum / count

ตัวอย่างโค้ด

<!DOCTYPE html>
<html lang="th">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>คำนวณค่าเฉลี่ย</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>คำนวณค่าเฉลี่ยของอาร์เรย์</h1>
  <div><pre class="sample"></pre></div>
  <div class="result"></div>
  <button class="Btn">ตรวจสอบ</button>
  <h3>กดปุ่มเพื่อคำนวณค่าเฉลี่ย</h3>
  <script>
    const resEle = document.querySelector(".result");
    const btnEle = document.querySelector(".Btn");
    const sampleEle = document.querySelector(".sample");
    const arr = [1, 2, 3, 4, 5, 11, 22];
    sampleEle.innerHTML = "[" + arr.join(", ") + "]";
    btnEle.addEventListener("click", () => {
      const sum = arr.reduce((acc, val) => acc + val, 0);
      const avg = sum / arr.length;
      resEle.innerHTML = "ค่าเฉลี่ย = " + avg;
    });
  </script>
</body>
</html>

ผลลัพธ์

คำนวณค่าเฉลี่ย (Average) ของอาร์เรย์ใน JavaScript

เมื่อกดปุ่ม "ตรวจสอบ":

คำนวณค่าเฉลี่ย (Average) ของอาร์เรย์ใน JavaScript

วิธีการต่างๆ

// 1. reduce (แนะนำ - ทำได้ใน 1 บรรทัด)
const avg = arr.reduce((a, b) => a + b, 0) / arr.length;

// 2. forEach
let sum = 0;
arr.forEach(v => sum += v);
const avg2 = sum / arr.length;

// 3. for...of (ทันสมัย อ่านง่าย)
let sum3 = 0;
for (const v of arr) sum3 += v;
const avg3 = sum3 / arr.length;

// 4. ลองใช้ library (lodash, mathjs) สำหรับสถิติซับซ้อน

ฟังก์ชันสำเร็จรูป

function average(arr) {
  if (!arr.length) return NaN;
  return arr.reduce((a, b) => a + b, 0) / arr.length;
}

// ใช้งาน
console.log(average([1, 2, 3, 4, 5])); // 3
console.log(average([])); // NaN

ค่าเฉลี่ยแบบอื่น (สำหรับสถิติขั้นสูง)

  • ค่าเฉลี่ยเรขาคณิต (Geometric Mean): ใช้สำหรับอัตราการเติบโต — Math.pow(arr.reduce((a,b)=>a*b), 1/arr.length)
  • ค่าเฉลี่ยฮาร์มอนิก (Harmonic Mean): ใช้สำหรับอัตรา/ความเร็ว — arr.length / arr.reduce((a,b)=>a+1/b, 0)
  • ค่าเฉลี่ยน้ำหนัก (Weighted Mean): แต่ละค่ามีน้ำหนักต่างกัน