**我该如何编写使用javascript中的for ... of产生Fibonacci的程序?
我已经尝试过了,效果很好
function createFibonacci(number) {
var i;
var fib = []; // Initialize array!
fib[0] = 0;
fib[1] = 1;
for (i = 2; i <= number; i++) {
// Next fibonacci number = previous + one before previous
// Translated to JavaScript:
fib[i] = fib[i - 2] + fib[i - 1];
console.log(fib[i]);
}
}
createFibonacci(8);
但是我想知道是否可以使用 for..of 编写它,有什么办法吗?
答案 0 :(得分:1)
这里是一个选择,使用generator:
function createFibonacci(number) {
// fibonacci generator
const gen = (function *(i) {
let a = 1, b = 1, c;
if (i--) yield a;
if (i--) yield b;
while (i--) {
yield c = a + b;
[a, b] = [b, c];
}
});
for (let f of gen(number)) {
console.log(f);
}
}
createFibonacci(8);
正如@T.J. Crowder所述,for...of
循环仅用于消耗序列,该序列实际上是由生成器生成的。
答案 1 :(得分:0)
您可以带发电机。
function* createFibonacci(number, a = 0, b = 1) {
if (a === 0)
if (number--) yield 1;
else return;
if (!number--) return
yield a + b;
yield* createFibonacci(number, b, a + b);
}
console.log(...createFibonacci(0));
console.log(...createFibonacci(1));
console.log(...createFibonacci(2));
console.log(...createFibonacci(3));
console.log(...createFibonacci(4));
console.log(...createFibonacci(5));
console.log(...createFibonacci(6));
console.log(...createFibonacci(7));
console.log(...createFibonacci(8));
.as-console-wrapper { max-height: 100% !important; top: 0; }
Rup稍有帮助的另一种方法。
function* createFibonacci(number, index = 1) {
createFibonacci.values = createFibonacci.values || [0, 1];
for (; index < createFibonacci.values.length && index < number + 1; ++index)
yield createFibonacci.values[index];
if (index >= number + 1) return;
yield createFibonacci.values[index] = createFibonacci.values[index - 2] + createFibonacci.values[index - 1];
yield* createFibonacci(number, index + 1);
}
console.log(...createFibonacci(0));
console.log(...createFibonacci(1));
console.log(...createFibonacci(2));
console.log(...createFibonacci(3));
console.log(...createFibonacci(4));
console.log(...createFibonacci(5));
console.log(...createFibonacci(6));
console.log(...createFibonacci(7));
console.log(...createFibonacci(8));
.as-console-wrapper { max-height: 100% !important; top: 0; }