JavaScript 斐波那契
本教程将讨论如何使用 JavaScript 中的循环生成斐波那契数列。
在 JavaScript 中使用循环生成斐波那契数列
在斐波那契数列中,第一个和第二个值是 0 和 1,所有其他值将根据前两个值计算。例如,斐波那契数列的第三个值是前两个值的和,依此类推。
要在 JavaScript 中生成斐波那契数列,我们必须定义前两个值,然后我们将使用一个循环,通过将序列的前两个值相加来生成其余的值。例如,让我们在 JavaScript 中生成斐波那契数列的前五个值。请参考下面的代码。
var fibonacci = [];
fibonacci[0] = 0;
fibonacci[1] = 1;
for (var i = 2; i < 5; i++) {
fibonacci[i] = fibonacci[i - 2] + fibonacci[i - 1];
}
console.log(fibonacci);
输出:
(5) [0, 1, 1, 2, 3]
正如你在输出中看到的,斐波那契数列的前五个值已经生成。我们也可以使用上面的代码创建一个函数,所以我们只需要将我们想要生成的值的数量提供给将生成斐波那契数列的函数。例如,让我们让函数生成给定值的斐波那契数列,并测试它生成 10 个值并使用 console.log()
函数在控制台上显示结果。请参考下面的代码。
function GenerateFibonacci(number) {
var fibonacci = [];
fibonacci[0] = 0;
fibonacci[1] = 1;
for (var i = 2; i < number; i++) {
fibonacci[i] = fibonacci[i - 2] + fibonacci[i - 1];
}
return fibonacci;
}
var f = GenerateFibonacci(10);
console.log(f);
输出:
(10) [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
正如你在输出中看到的,斐波那契数列的前十个值已经生成。你可以使用此函数生成任意数量的斐波那契数列值。
相关文章
Do you understand JavaScript closures?
发布时间:2025/02/21 浏览次数:108 分类:JavaScript
-
The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.
Do you know about the hidden traps in variables in JavaScript?
发布时间:2025/02/21 浏览次数:178 分类:JavaScript
-
Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av
How much do you know about the Prototype Chain?
发布时间:2025/02/21 浏览次数:150 分类:JavaScript
-
The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start
用 jQuery 检查复选框是否被选中
发布时间:2024/03/24 浏览次数:102 分类:JavaScript
-
在本教程中学习 jQuery 检查复选框是否被选中的所有很酷的方法。我们展示了使用直接 DOM 操作、提取 JavaScript 属性的 jQuery 方法以及使用 jQuery 选择器的不同方法。你还将找到许多有用的
jQuery 中的 Window.onload 与 $(document).ready
发布时间:2024/03/24 浏览次数:180 分类:JavaScript
-
本教程演示了如何在 jQuery 中使用 Window.onload 和 $(document).ready 事件。