【发布时间】:2018-08-30 22:39:33
【问题描述】:
我正在尝试构建一个简单的卡路里计算器,但出于某种奇怪的原因,我的总卡路里(卡路里,一个整数,减去卡路里扣除,一个整数)的数学一直返回 NaN。谁能告诉我我错过了什么?我已经在输入的卡路里和卡路里扣除上测试了 console.log 输出,它们都以整数形式返回。我不明白为什么从另一个中减去一个会返回 NaN,除非我需要手动将 totalCalories 定义为整数。我是新手,所以我不一定确定最好的方法。任何帮助表示赞赏。谢谢!
var maxCaloriesCodes = ['FMW', 'FLW', 'MMW', 'MLW'];
var maxCaloriesAllowed = [2000, 1500, 2500, 2000];
var exerciseCodes = ['FL', 'FM', 'FV', 'ML', 'MM', 'MV'];
var exerciseCalories = [240, 370, 580, 300, 460, 730];
function performAssessment(){
var genderElem = document.getElementById('gender_id');
var genderValue = genderElem.options[genderElem.selectedIndex].value;
var genderText = genderElem.options[genderElem.selectedIndex].text;
var goalElem = document.getElementById('goal_id');
var goalValue = goalElem.options[goalElem.selectedIndex].value;
var goalText = goalElem.options[goalElem.selectedIndex].text;
var exerciseElem = document.getElementById('exercise_id');
var exerciseValue = exerciseElem.options[exerciseElem.selectedIndex].value;
var exerciseText = exerciseElem.options[exerciseElem.selectedIndex].text;
var caloriesCode = genderValue + goalValue;
var caloriesAllowed;
var completeExerciseCodes = genderValue + exerciseValue;
var calorieDeduction;
var totalCalories;
// Loop through the array and locate the code to get the maximum calories
for (var codeCount = 0; codeCount < maxCaloriesCodes.length; codeCount++) {
// Determine if the current code is the array
if (maxCaloriesCodes[codeCount] == caloriesCode) {
caloriesAllowed = maxCaloriesAllowed[codeCount];
}
}
totalCalories = (calories - calorieDeduction);
// Loop through my exercise arrays and locate codes for calorie deductions
for (var codeCount = 0; codeCount < exerciseCodes.length; codeCount++){
// Determine if the current code is in the array
if (exerciseCodes[codeCount] == completeExerciseCodes) {
calorieDeduction = exerciseCalories[codeCount];
}
}
console.log(totalCalories)
}
【问题讨论】:
-
calorieDeduction在哪里初始化?如果它没有明确设置为something,它的值将是undefined,减法会给你NaN。 -
你说的是
totalCalories = (calories - calorieDeduction);在您定义calorieDeduction是什么之前 -
calorieDeduction没有设置为任何值,所以它是undefined。 -
它是在我的 for 循环中初始化的,但我在循环之前定义了 totalCalories。我移动了这条线并修复了它。谢谢!
-
许多 cmets 应该/可能是答案。
标签: javascript