JavaScript:尝试减去两个变量会为我返回NaN

时间:2018-08-30 14:25:55

标签: javascript

我正在尝试构建一个简单的卡路里计算器,出于某种奇怪的原因,我的totalCalories(即卡路里,一个整数,减去卡路里扣除,一个整数)的数学一直返回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)
}

1 个答案:

答案 0 :(得分:0)

除了循环,if子句或函数调用外,代码从上到下逐行执行。在执行totalCalories = (calories - calorieDeduction)的行中,caloriescalorieDeduction都没有值。或者实际上,它们的值为undefined,为您提供NaN。