如果我对索引进行硬编码,它会按预期工作,为什么这个增量器会返回NAN

Why is this incrementer returning NAN when if I hard code the index it works as expected?

本文关键字:工作 为什么 NAN 返回 索引 如果 编码      更新时间:2023-11-26

我试图做一个简单的阶乘代码挑战,但使用Javascript,当我试图通过循环索引来获得索引位置时,我得到了NAN。我知道NAN属于数字类型,只是Javascript不知道是哪个数字。我不明白为什么这种情况会发生。此外,我如何使用Javascript中的循环来获取数组的索引?谢谢

// Input = 4 Output = 24
// Input = 8 Output = 40320
var total = 0;
var factor_Array = [];
function FirstFactorial(num) {
  for (var i = 1; i <= num; i++){
    factor_Array.unshift(i);
    // console.log(factor_Array);
  }
  for (var j = 0; j < factor_Array.length; j++){
    // Why does this work??? But not when I use 'j' to grab the index    position?  Seems like BOTH ways should work
    total = factor_Array[0] * factor_Array[0+1];
    total = factor_Array[j] * factor_Array[j+1];
  }
 console.log(total);
 //return num;
}
FirstFactorial(4);

因为当j = (factor_Array.length-1)时,它试图访问不存在的j+1元素。

以下将如您所期望的一样工作

for (var j = 0; j < (factor_Array.length-1); j++){
    total = factor_Array[j] * factor_Array[j+1];
}

循环时

for (var j = 0; j < factor_Array.length; j++){
    total = factor_Array[j] * factor_Array[j+1];
}

然后,在最后一次迭代中,自以来,您将超出数组边界

j = factor_Array.length - 1

并且您正在访问j + 1