JavaScript에서 배열의 평균값을 구하는 것은 매우 간단합니다. 기본 원리는 배열의 모든 요소를 더한 뒤, 그 합을 요소 개수로 나누는 것입니다. forEach() 메서드를 사용하면 반복문 없이도 깔끔하게 합계를 구할 수 있습니다.
아래는 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>코드 설명
이 코드의 동작 방식은 다음과 같습니다.
먼저 [1, 2, 3, 4, 5, 11, 22]라는 숫자 배열을 생성하고, 이를 화면에 표시합니다. 버튼을 클릭하면 클릭 이벤트 리스너가 실행되어 forEach() 메서드가 배열의 각 요소를 순회하며 sum 변수에 값을 더해 합계를 계산합니다. 마지막으로 총합을 arr.length(배열 길이)로 나눈 결과를 화면에 출력합니다.
참고로 ES6 이상 환경에서는 reduce() 메서드를 활용해 한 줄로 처리할 수도 있습니다.
const avg = arr.reduce((a, b) => a + b, 0) / arr.length;
출력 결과

'Check' 버튼을 클릭하면 아래와 같이 배열의 평균값이 화면에 표시됩니다.
