Trung bình cộng = tổng các phần tử / số lượng phần tử. Dùng forEach hoặc reduce để tính tổng.
Ví dụ
Tính trung bình mảng [1, 2, 3, 4, 5, 11, 22]:
<!DOCTYPE html>
<html lang="vi">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Tính trung bình mảng</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>Tính trung bình của mảng</h1>
<div><pre class="sample"></pre></div>
<div class="result"></div>
<button class="Btn">TÍNH TRUNG BÌNH</button>
<h3>Nhấn nút để tính trung bình mảng trên</h3>
<script>
const resEle = document.querySelector(".result");
const btn = document.querySelector(".Btn");
const sampleEle = document.querySelector(".sample");
const arr = [1, 2, 3, 4, 5, 11, 22];
sampleEle.innerHTML = `[${arr.join(', ')}]`;
btn.addEventListener("click", () => {
const sum = arr.reduce((acc, val) => acc + val, 0);
const avg = sum / arr.length;
resEle.innerHTML = `Trung bình cộng = ${avg}`;
});
</script>
</body>
</html>
Kết quả
Tổng = 48, số phần tử = 7 -> Trung bình = 6.857...
Lưu ý: Nên kiểm tra arr.length > 0 để tránh chia cho 0.