我正在寫一個函數在Javascript中,將採取一個數字,然後返回有多少正方形有一個長方形。例如,通過1會給你一個,2會給你5,3會給你14等等。問題是,我得到了楠的結果。我不確定它會從哪裏得到除了數字之外的任何東西。NaN結果與獨特的方塊
function a (n)
{
if (n > 0)
{
var total = n*n;
total += a(n-1);
return (total);
}
}
document.write(a(10));
我正在寫一個函數在Javascript中,將採取一個數字,然後返回有多少正方形有一個長方形。例如,通過1會給你一個,2會給你5,3會給你14等等。問題是,我得到了楠的結果。我不確定它會從哪裏得到除了數字之外的任何東西。NaN結果與獨特的方塊
function a (n)
{
if (n > 0)
{
var total = n*n;
total += a(n-1);
return (total);
}
}
document.write(a(10));
我不知道它會獲得任何東西,除了從一些。
您的基本情況丟失,它返回undefined
。嘗試
function a(n) {
if (n > 0)
return n*n + a(n-1);
else
return 0;
}
這是因爲if (n > 0)
的。當這不是真的你的函數返回void
。所以請將0
退還給您。
function a (n)
{
if (n > 0)
{
var total = n*n;
total += a(n-1);
return total;
}
else
{
return 0;
}
}
console.log(a(10));
您已經有了兩個很好的答案。我只是想讓你知道以更面向對象的風格寫作。如果事情變得更加複雜,將變量和函數組合在一起並使它們遠離其他所有東西變得更容易。我會寫這樣的東西,以保持它的組織:
var a = {
total: 0,
sides: function (n) {
if (n > 0) {
this.total = n * n;
this.total += this.sides(n - 1);
return this.total;
} else {
return 0
}
}
}
a.sides(5);
alert(a.total);
看看你的函數在'n == 0'時返回的值。 – Bergi 2015-02-10 22:53:11