📅  最后修改于: 2023-12-03 15:15:03.798000             🧑  作者: Mango
The Fibonacci sequence is a series of numbers where each number is the sum of the two preceding ones, starting from 0 and 1. It is named after Italian mathematician Leonardo of Pisa, who was known as Fibonacci.
In this article, we will explore how to generate the Fibonacci sequence using Javascript.
Here is a simple Javascript function that generates the Fibonacci sequence:
function fibonacci(n) {
if (n === 0) {
return [0];
} else if (n === 1) {
return [0, 1];
} else {
const sequence = fibonacci(n - 1);
sequence.push(sequence[sequence.length - 1] + sequence[sequence.length - 2]);
return sequence;
}
}
The function takes a parameter n
which specifies how many numbers in the sequence to generate. If n
is 0, it returns an array containing only 0. If n
is 1, it returns an array containing 0 and 1. Otherwise, it recursively calls itself with n-1
and then adds the sum of the last two numbers in the resulting sequence to generate the next number in the sequence.
To use the fibonacci
function, simply call it with the desired number of elements:
const sequence = fibonacci(10);
console.log(sequence);
// Output: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
The code above generates a Fibonacci sequence with 10 numbers and logs it to the console.
Generating the Fibonacci sequence using Javascript is a simple task that can be accomplished with a recursive function. Knowing how to generate this sequence can be useful in many areas of programming, including algorithms and mathematical modeling.