你的函數可以return
一個值,你可以在一個變量存儲:
fib = function(numMax){
var sum = 0;
for(i=0,j=1,k=0; k<numMax;i=j,j=x,k++){
var x = i + j;
if (x % 2 === 0){
sum += x; // This is the same like sum = sum + x;
}
}
return sum; // Let's return the calculated sum as the result of the function
};
var result = fib(32); // result contains the value the function returned
console.log(result);
我不知道你問題的第二部分。你想要,那numMax不能大於999999?
fib = function(numMax){
if (numMax > 999999) {
numMax = 999999;
}
var sum = 0;
for(i = 0, j = 1, k = 0; k < numMax; i = j, j = x, k++){
var x = i + j;
if (x % 2 === 0){
sum += x; // This is the same like sum = sum + x;
}
}
return sum; // Let's return the calculated sum as the result of the function
};
var result = fib(32); // result contains the value the function returned
console.log(result);
您正在尋找[了'return'聲明。(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/return) – Pointy
我看。你能舉例說明我如何在這種情況下應用它?我只能打印第一個數字。 – tklein
我猜是什麼問題?目前控制檯日誌是將這些值打印到控制檯。 – Damon