单击按钮以获取前 12 个斐波那契数的总和
Click button to get the sum of the first 12 Fibonacci numbers
我想获取并添加前 12 个偶数斐波那契数,并在单击按钮时将其显示在我的页面上。现在我的代码获取并添加偶数。如何将其限制为前 12 个偶数?
提前谢谢你。 http://jsfiddle.net/lakenney/oryygn4y/
// first we get the HTML for the button
var getFibSum = document.getElementById("sumFib");
//then we set the event handler for when the button is clicked
getFibSum.onclick = function(){
document.getElementById("sumFibResult").innerHTML = twelveEvenFibonacciSum();
}
/*
* twelveEvenFibonacciSum - calulates the sum of the first 12 even fibonacci numbers, with 0, 1 being the first two numbers of the sequence
*/
function twelveEvenFibonacciSum(){
/// WRITE YOUR CODE HERE
// Loop that generates Fibonacci numbers.
console.clear();
var fib = [0, 1]; //Initialize array
var sum = 0;
for (var i= 2; i <= 50; i++) {
fib[i] = fib[i-1] + fib[i-2];
var integer = fib[i];
if(integer % 2 == 0) {
// console.log("my current even fib is " + fib[i]);
var sumFibResult = sum += fib[i];
console.log("my current even fib added to sum " + sumFibResult);
}
// Loop until we have 12 even numbers
}
//console.log(fib);
return sumFibResult;
}
向外部作用域添加一个变量,每次调用函数时,该变量都会递增。当此值等于 12 时返回。
for (var i= 2; i <= 50; i++) {
fib[i] = fib[i-1] + fib[i-2];
var integer = fib[i];
if(integer % 2 == 0) {
// console.log("my current even fib is " + fib[i]);
var sumFibResult = sum += fib[i];
console.log("my current even fib added to sum " + sumFibResult);
timesIncremented++;
}
// Loop until we have 12 even numbers
if(timesIncremented >= 12) {
return;
}
}
相关文章:
- 通过单击提交按钮获取表单名称
- 从按钮获取文本
- 我可以使用ajax按钮获取下拉值并填写表单吗
- 使用Javascript从按钮获取自定义属性
- 使用按钮获取HTML表中的值
- 从多个按钮获取价值
- 如何从单击按钮获取值
- 从选中的单选按钮获取文本节点
- 无法从表内的按钮获取行 ID
- 如何通过单击按钮获取单元格值
- 通过 PHP 中的对象从提交按钮获取 POST
- 使用按钮获取谷歌地图上的json数据和过滤标记
- 如何从人工任务表单中的单选按钮获取检查值
- “$.getScript @href”不会从按钮获取 href,只会从 a 标记中获取
- 使用 2 个按钮获取 2 个不同控制器的 1 个输入字段值
- 使用 JavaScript 从 HTML 按钮获取值
- 点击按钮获取当前系统日期时间
- 如何从服务器端的这些按钮获取信息
- 如何从提交按钮获取formmethod和formaction
- 发送<表单>通过两个不同的Submit按钮获取信息,这两个按钮调用相同的函数,但需要知道调用来自哪个Subm