【问题标题】:JavaScript: Trying to subtract two variables returns NaN for meJavaScript:尝试减去两个变量为我返回 NaN
【发布时间】: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


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2022-06-14
    • 2014-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-03
    相关资源
    最近更新 更多