因此,我使用JS创建了一个非常基本的bmi计算器。我已经创建了一个函数,然后尝试使用该函数的名称(bmiCalculator)重新调用它。据我所知,这应该会给我带来正确的回报。
我寻找并找到了解决方案,但只是想了解为什么函数需要重复运行函数?
function bmiCalculator(weight, height) {
var bmi = Math.round(weight / Math.pow(height, 2));
var interpretation;
if (bmi < 18.5) {
interpretation = "Your BMI is " + bmi + ", so you are underweight.";
}
if (bmi >= 18.5 && bmi < 24.9) {
interpretation = "Your BMI is " + bmi + ", so you have a normal weight.";
}
if (bmi >= 25) {
interpretation = "Your BMI is " + bmi + ", so you are overweight.";
}
return interpretation;
};
bmiCalculator(68, 1.73);
function bmiCalculator(weight, height) {
var bmi = Math.round(weight / Math.pow(height, 2));
var interpretation;
if (bmi < 18.5) {
interpretation = "Your BMI is " + bmi + ", so you are underweight.";
}
if (bmi >= 18.5 && bmi < 24.9) {
interpretation = "Your BMI is " + bmi + ", so you have a normal weight.";
}
if (bmi >= 25) {
interpretation = "Your BMI is " + bmi + ", so you are overweight.";
}
return interpretation
};
bmiCalculator(45, 1.65);
发布于 2020-10-11 22:01:51
不,您不必重复函数。下面的代码应该可以很好地工作:
function bmiCalculator(weight,height) {
var bmi = Math.round(weight / Math.pow(height,2));
var interpretation;
if (bmi < 18.5) {
interpretation = "Your BMI is " + bmi + ", so you are underweight.";
}
if (bmi >= 18.5 && bmi < 24.9) {
interpretation ="Your BMI is " + bmi + ", so you have a normal weight.";
}
if (bmi >= 25) {
interpretation ="Your BMI is " + bmi + ", so you are overweight.";
}
return interpretation;
};
bmiCalculator(68,1.73);
bmiCalculator(45,1.65); 您可以将结果保存到变量,例如:
const bmi1 = bmiCalculator(68,1.73);
const bmi2 = bmiCalculator(45,1.65);
console.log(bmi1);
console.log(bmi2);发布于 2020-10-11 21:58:30
我运行了代码,它工作得很好。您应该使用console.log并查看代码的ruslts。在chrome中,你可以按F12来打开控制台,然后当你使用console.log(bmiCalculator(68,1.73));时,它会打印出BMI。您可以在第一次函数调用后删除代码。
https://stackoverflow.com/questions/64304693
复制相似问题