Is there a way for me to receive numerical values instead of NaN?

I'm currently facing a challenge in creating a Fibonacci number generator and I've hit a roadblock. It seems like I have a solution, but the appearance of NaN's is causing me some trouble.

function fibonacciGenerator (n) {

   var output = [];

 if( n === 2 ){
       output.push(0,1);
   }
  else if( n === 1 ){
       output.push(0);
       } 

else{
output = [0,1];
 while( n > output.length){
                    
         output.push((output[output.length - 2]) + (output[output.lenght - 1]));
     }
  
 }
     
   
     
   return output
   
   
  
}

So, when I use the function with n=3 and higher, it adds the sum of the last two numbers in the output array to that array until n<output.length. Everything works as expected, the loop stops when n=output.lenght, but I keep getting back NaN's instead of numbers. What could I be doing incorrectly?

Answer №1

There is a spelling error in the word "lenght" - it should be "length"

while( n > output.length){
                    
         output.push((output[output.length - 2]) + (output[output.length - 1]));
     }
  
 }

Answer №2

function generateFibonacciSequence(num) {

    var result = [];

    if (num === 2) {
        result.push(0, 1);
    }
    else if (num === 1) {
        result.push(0);
    }

    else {
        result = [0, 1];
        while (num > result.length) {
            // issue here was a typo in result.length
            result.push((result[result.length - 2]) + (result[result.length - 1]));
        }

    }
    return result;
}

console.log(generateFibonacciSequence(5));

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for halting click propagation in VueJS

My dilemma lies within a recursive list (tree) where each element contains a @click="sayHello(el.id)". The challenge arises due to the nested structure of the list, such as: list-element-0-01 ├──list-el-1-01 │ └──list-el-2-01 └──list ...

Issues with Select2 Ajax functionality not functioning as intended

I am currently using the select2 library to create a dropdown menu with ajax functionality, but I am encountering some issues. Below is my code: $("#guests").select2({ multiple: true, minimumInputLength: 1, formatInputTooShort: fun ...

Utilizing Node.js and Jasmine: Preventing the invocation of a Promise function to avoid executing the actual code results in DEFAULT_TIMEOUT_INTERVAL

There is a function below that returns a promise. public async getAverageHeadCount(queryParams: Params, childNode: any, careerTrackId: string): Promise<Metric> { const queryId = this.hierarchyServiceApiUrl + "rolling-forecast/ahc/" + q ...

Preventing page navigation in JavaScript: Why it's so challenging

I am encountering an issue with a link element that I have bound a click event to (specifically, all links of a certain class). Below is an example of the link element in question: <a id="2" class="paginationclick" style="cursor: pointer;" href=""> ...

Webpack: Live reloading is not functioning properly, however the changes are still successfully compiling

Could someone help me understand why my React application, set up with Webpack hot reload, is not functioning properly? Below is the content of my webpack.config.js: const path = require('path'); module.exports = { mode: 'development&apo ...

Unveiling the method to fetch the emitted value from a child component and incorporate it into the parent component's return data in Vue

How can I retrieve the title value passed by the Topbar component and incorporate it into the data() return section? I attempted to create a method to pass the value, but was unsuccessful despite being able to successfully log the value in the parent file. ...

Loading message displayed in web browsers by banner rotation system

I'm currently working on a banner rotator function that seems to be showing a "loading" message continuously while running. Here is the code snippet for reference: var banners = ['../Graphics/adv/1.gif','../Graphics/adv/2.jpg']; / ...

Error: The function **now.toUTCString** is not recognized and cannot be executed by HTMLButtonElement

While the JavaScript code runs smoothly without setting a time zone, I encountered an error when trying to display the Barbados time zone. The issue is related to now.toUTCString function throwing the following error message. How can I resolve this? Uncau ...

Sending a function return to a React component

What I want to achieve is sending the response from an API call to a React Component and using it to generate a List. My confusion lies in how to pass the value from a function to the component. Do I require state for this process? searchMealsHandler(even ...

Collapsing or expanding the Material UI accordion may lead to flickering on the page

import React from "react"; import { makeStyles } from "@material-ui/core/styles"; import Accordion from "@material-ui/core/Accordion"; import AccordionDetails from "@material-ui/core/AccordionDetails"; import Accordi ...

Persistent error function arises from Ajax request in Laravel

Greetings everyone. I'm currently working on my Laravel application and trying to verify the attendance for a specific date, subject, grade in my database table. If the data exists, I have implemented an if statement to display the desired results bas ...

What is the best way to create a line graph with D3.js in order to display data that is obtained from a server-side source?

I am trying to access data from a server side link, which is as follows: The data I want to retrieve is in JSON format and looks like this: {"Id":466,"Name":"korea", "Occurren ...

How can jQuery input be incorporated in a form submission?

My current form includes a field for users to input an address. This address is then sent via jQuery.ajax to a remote API for verification and parsing into individual fields within a JSON object. I extract the necessary fields for processing. I aim to sea ...

Achieving a single anchor link to smoothly scroll to two distinct sections within a single page using React

There is a sidebar section alongside a content section. The sidebar contains anchor links that, when clicked, make the corresponding content scroll to the top on the right-hand side. However, I also want the sidebar link that was clicked to scroll to the ...

Leveraging the keyword 'this' within an object method in node's module.exports

My custom module: module.exports = { name: '', email: '', id: '', provider: '', logged_in: false, checkIfLoggedIn: function(req, res, next){ console.log(this); } }; I inclu ...

The "require" keyword cannot be used in a Node-RED Function node

When working with a Node-RED Function Node, the first line I include is: var moment = require('moment-timezone'); I'm attempting to create a timezone accurate date/time stamp for sensor data. However, when this node runs, I encounter the fo ...

Retrieve the initial value from the TextField

My website features multiple filters, including by date and duration, allowing users to easily find the information they need from a large dataset. There is also a "reset all filters" button that clears all filters and displays the full list of products. ...

The element is being offset by SVG animation that incorporates transform properties

I'm working on creating a halo effect by rotating an SVG circular element using the transform rotate function. I've been using getBox to find the center point of the element, but when the rotation occurs, the overall image is getting misaligned w ...

React and D3 Force Layout: uncharted territories for new links' positions

After carefully following the general update pattern for new React Props, I've noticed that D3 efficiently handles data calculation and rendering when receiving new props. This prevents React from having to render every tick. D3 functions seamlessly ...

The React component continuously refreshes whenever the screen is resized or a different tab is opened

I've encountered a bizarre issue on my portfolio site where a diagonal circle is generated every few seconds. The problem arises when I minimize the window or switch tabs, and upon returning, multiple circles populate the screen simultaneously. This b ...