3 回答

TA贡献1860条经验 获得超9个赞
let gender;
let caloriesMen = 2500;
let caloriesWomen = 2000;
let caloriesToday;
let caloriesLeft;
function calCalc() {
gender = prompt('Are you man or woman?')
if (gender == 'man') {
caloriesToday = prompt('How many calories have you already consumed today?');
caloriesLeft = caloriesMen - caloriesToday;
alert('You have ' + caloriesLeft + ' calories left to consume today!');
} else if (gender == 'woman') {
caloriesToday = prompt('How many calories have you already consumed today?');
caloriesLeft = caloriesWomen - caloriesToday;
alert('You have ' + caloriesLeft + ' calories left to consume today!');
}
}
calCalc();

TA贡献1848条经验 获得超10个赞
您需要初始化变量以避免undefined值污染它所接触的所有内容。
“更清晰的代码”是一个品味问题。我个人会避免使用带有不同性别键的对象的 if/else。如果没有必要,不要使用全局变量。在函数内定义变量效果很好。
function calCalc() {
let gender = prompt('Are you man or woman?');
let caloriesPerGender = {'man': 2500, 'woman': 2000};
let caloriesToday = prompt('How many calories have you already consumed today?');
alert('You have ' + (caloriesPerGender[gender] - caloriesToday) + ' calories left to consume today!');
}
calCalc();
您可能还想检查您的输入,如果有人在性别上输入“monkey”或在卡路里输入中输入“abc”,您的函数将会崩溃。
添加回答
举报