为什么我的函数过多地推一个值?

时间:2019-05-31 16:46:33

标签: javascript fibonacci

我正在尝试编写自己的斐波那契函数。它应返回数组中小于num的所有斐波那契数。我尝试通过currentPush循环将numwhile进行比较,但它对返回的数组推入的值太多了。

我的代码有什么问题?它应该在最后一次迭代之前停止,因为currentPush肯定大于num

function fib(num) {

  if(num < 2){return 1};

  let fib = [1, 1];
  let currentPush = 2;

  while (currentPush < num){
    // get last two elements from array and add them together
    currentPush = fib.slice(fib.length-2, fib.length).reduce((a, b) => a + b);
    fib.push(currentPush);
  }

  return fib;
}
 console.log(fib(10)); // [ 1, 1, 2, 3, 5, 8, 13 ]
 console.log(fib(100)); // [ 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144 ]

1 个答案:

答案 0 :(得分:1)

正如评论所提到的,在推入数组之前但在计算currentPush < num之后,您必须检查currentPush

function fib(num) {

  if(num < 2) {return 1};

  let fib = [1, 1];
  
  while (true) {
    let currentPush = fib.slice(fib.length-2, fib.length).reduce((a, b) => a + b);
    if (currentPush > num)
      return fib;
    fib.push(currentPush);
  }
}

console.log(fib(10)); // [ 1, 1, 2, 3, 5, 8, 13 ]
console.log(fib(100)); // [ 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144 ]