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”,您的函數將會崩潰。
添加回答
舉報