Javascript/变量位置/代码有什么问题



我想用Javascript写一个斐波那契数生成器;0、1、1、2、5、7、12…(要得到这个数列,你必须把最后两个数字加起来)但是我在分配输出时遇到了这个问题。如果我直接写下来,而不是写newnumber,代码就不会起作用了。代码下来是然而工作,但我不明白什么是错误的第一个。变量的位置有问题吗?

function fibonacciGenerator(n) {
var output = [];
var lastNumber = output[output.length - 1];
var nPrev = output[output.length - 2];
var newNumber = lastNumber + nPrev;
if (n === 1) {
output = [0];
} else if (n === 2) {
output = [0, 1];
} else {
output = [0, 1];
for (var i = 2; i < n; i++) {
output.push(newNumber);
}
}
return output
}
console.log(fibonacciGenerator(5));

function fibonacciGen(n) {
const output = [0, 1];
// Return an empty array if n is less than 1
if (n < 1) {
return [];
}

// If n is 1 or 2, we can return the array now
if (n <2) {
return output;
}
// Loop through the remaining numbers in the sequence
for (let i = 2; i < n; i++) {
// Calculate the next number in the sequence
let lastNumber = output[output.length - 1];
let nPrev = output[output.length - 2];
let newNumber = lastNumber + nPrev;
// Add the new number to the output array
output.push(newNumber);
}

// Return the output array
return output;
}
console.log(fibonacciGen(5));

你必须在循环中声明下一项的逻辑,因为第一次输出的时间长度为零

function fibonacciGenerator (n) {
var output =[]; 

if (n < 1) {
return [];
}
if (n===1){
output=[0];
}
else if (n===2){
output=[0,1];
}
else{ 
output=[0,1];
for( var i = 2; i < n; i++){
var lastNumber=output[output.length-1];
var nPrev=output[output.length-2];
var newNumber=lastNumber+nPrev;
output.push(newNumber);
}
}
return output  
}

最新更新