다음은 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 median of an array</h1> <div><pre class="sample"></pre></div> <div class="result"></div> <button class="Btn">Calculate</button> <h3>Click on the above button to calculate the median of the above array</h3> <script> let resEle = document.querySelector(".result"); let BtnEle = document.querySelector(".Btn"); let sampleEle = document.querySelector(".sample"); let arr = [1, 5, 6, 99, 12, 11, 22]; sampleEle.innerHTML = arr; BtnEle.addEventListener("click", () => { let middle = Math.floor(arr.length / 2); arr = [...arr].sort((a, b) => a - b); if (arr.length % 2 !== 0) { resEle.innerHTML = "Median = " + arr[middle]; } else { resEle.innerHTML = "Median = " + (arr[middle - 1] + arr[middle]) / 2; } }); </script> </body> </html>