js实现Bmi计算
以下是用JavaScript实现BMI计算的几种方法:
基础计算函数
function calculateBMI(weight, height) {
const bmi = weight / (height * height);
return bmi.toFixed(2);
}
完整BMI计算器(带分类)
function getBMICategory(bmi) {
if (bmi < 18.5) return 'Underweight';
if (bmi < 25) return 'Normal weight';
if (bmi < 30) return 'Overweight';
return 'Obese';
}
function fullBMICalculator(weightKg, heightM) {
const bmi = calculateBMI(weightKg, heightM);
const category = getBMICategory(bmi);
return { bmi, category };
}
带单位转换的计算器
function calculateBMIWithUnits(weight, height, unitSystem = 'metric') {
let weightKg = weight;
let heightM = height;
if (unitSystem === 'imperial') {
weightKg = weight * 0.453592; // 磅转千克
heightM = height * 0.0254; // 英寸转米
}
return calculateBMI(weightKg, heightM);
}
HTML页面集成示例
<!DOCTYPE html>
<html>
<head>
<title>BMI Calculator</title>
</head>
<body>
<div>
<label>Weight (kg): <input type="number" id="weight"></label>
<label>Height (m): <input type="number" id="height"></label>
<button onclick="calculate()">Calculate BMI</button>
<div id="result"></div>
</div>
<script>
function calculate() {
const weight = parseFloat(document.getElementById('weight').value);
const height = parseFloat(document.getElementById('height').value);
const result = fullBMICalculator(weight, height);
document.getElementById('result').innerHTML =
`BMI: ${result.bmi} (${result.category})`;
}
</script>
</body>
</html>
使用时需要注意:
- 体重单位应为千克(kg)
- 身高单位应为米(m)
- 对于英制单位需要先进行转换
- BMI计算公式为:体重(kg)除以身高(m)的平方
BMI分类标准:
- 低于18.5:偏瘦
- 18.5-24.9:正常
- 25-29.9:超重
- 30及以上:肥胖







