JavaScript:返回 NAN 的函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12149945/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 15:26:47  来源:igfitidea点击:

JavaScript: function returning NAN

javascript

提问by Leahcim

I'm working on a codecademy.com lesson with instructions to write the calculateTotal function below. When I click run, it's returning NaN. Anyone know what's wrong with the calculateTotal function as I wrote it that's making it return NaN. Note, I understand that NaN means not a number...

我正在编写 codecademy.com 课程,其中包含编写下面的calculateTotal 函数的说明。当我单击运行时,它返回 NaN。任何人都知道我编写的calculateTotal 函数有什么问题,这使它返回NaN。请注意,我知道 NaN 表示不是数字......

// runner times
var carlos = [9.6,10.6,11.2,10.3,11.5];
var liu = [10.6,11.2,9.4,12.3,10.1];
var timothy = [12.2,11.8,12.5,10.9,11.1];

// declare your function calculateTotal here
var calculateTotal = function(raceTimes){
    var totalTime; 
    for(i = 0; i < raceTimes.length; i++){
        totalTime += raceTimes[i]; 
        return totalTime; 
    }
};

var liuTotal = calculateTotal(liu);

console.log(liuTotal);

Note, many of the people answering this question have said that var totalTime has to be set to "O". However, in the next codecademy lessson, the author writes a function with totalTime not set to anything and it works

请注意,许多回答这个问题的人都说 var totalTime 必须设置为“O”。但是,在接下来的 codecademy 课程中,作者编写了一个 totalTime 未设置为任何内容的函数,并且可以正常工作

var calculateAverage = function (raceTimes) {
  var totalTime;
  for ( i = 0; i < raceTimes.length; i++ ) {
    totalTime = (totalTime || 0) + raceTimes[i];
  }
// assign variable averageTime
var averageTime = totalTime / raceTimes.length; 

  return averageTime;
};

回答by Jamie Treworgy

Two problems:

两个问题:

  1. totalTimeis not defined -- adding something to an undefined results in NaN
  2. You are returning INSIDE your loop.
  1. totalTime未定义——向未定义的结果中添加内容 NaN
  2. 您正在循环内部返回。

Fix:

使固定:

var totalTime=0;
for(i = 0; i < raceTimes.length; i++){
    totalTime += raceTimes[i]; 
}
return totalTime; 

回答by Richard JP Le Guen

Your totalTimedoesn't have an initial value, so it starts off as undefined. You can't add a number to undefinedand get a number:

totalTime没有初始值,因此它以undefined. 您无法添加数字undefined并获得数字:

var totalTime; // implicitly initialized to undefined 
for(i = 0; i < raceTimes.length; i++){
    totalTime += raceTimes[i];  // undefined + raceTimes[i] = NaN
    return totalTime; 
}

Initialize it to 0.

将其初始化为0.

var totalTime = 0;

回答by 0x499602D2

You haven't initialized totalTimewith a value. So it defaults to undefined. Therefore on each iteration, undefined is being added, yielding NaN.

您尚未totalTime使用值进行初始化。所以它默认为undefined. 因此,在每次迭代中,都会添加 undefined ,从而产生NaN.