斐波那契数列 javascript 循环

问题描述 投票:0回答:2

我正在学习和练习斐波那契数列,但我不明白“i”值去了哪里?

function fibonacciGenerator (n) {
    
      var output = [];
  if (n === 1) {
    output = [0];
  }     
  else if (n === 2) {
      output = [0, 1];
  }
  else if (n === 0) {
      output = ["Please put in the number"];
  }
  else {
      output = [0, 1];
      for (var i = 2; i < n; i++) {
          output.push(output[output.length - 2] + output[output.length - 1]);
      }
      
  }
    return output;  
    
  console.log(output); 
}

所以问题线是这个循环

else {
      output = [0, 1];
      for (var i = 2; i < n; i++) {
          output.push(output[output.length - 2] + output[output.length - 1]);
      }

所以代码本身就理解 [0,1,...] 旁边的输出是“i”,对吗? 为什么我不能像这样放置这条线

else {
      output = [0, 1];
      for (var n = 2; n < output.length; n++) {
          output.push(output[output.length - 2] + output[output.length - 1]);
      }

(顺便说一句,它说“未捕获的引用错误:i未定义”)

javascript fibonacci
2个回答
0
投票
for (var n = 2; n < output.length; n++) {
      output.push(output[output.length - 2] + output[output.length - 1]);
  }

不起作用,因为 for 循环条件取决于数组长度 (

n < output.length
),并且您正在循环内修改数组长度。

对于 for 循环,您应该使用 'let' 而不是 'var',就像这样

for (let i = 2; i < n; i++) {
          output.push(output[output.length - 2] + output[output.length - 1]);
      }

查看这篇 stackoverflow 帖子,它详细解释了 'var' 和

之间的区别

0
投票

代码中的问题在于循环条件。您对函数参数和循环变量使用相同的变量 n。这可能会导致意外的行为。另外,循环条件 n < output.length will never be true because you are pushing elements into the output array, making its length always greater than 2.

else {
      output = [0, 1];
      for (var n = 2; n < output.length; n++) {
          output.push(output[output.length - 2] + output[output.length - 1]);
      }

使用下面的代码是正确的

else {
      output = [0, 1];
      for (var i = 2; i < n; i++) {
          output.push(output[output.length - 2] + output[output.length - 1]);
      }
© www.soinside.com 2019 - 2024. All rights reserved.