2013-07-08 28 views
10

このスニペットを実行すると、戻り前にconsole.logが値の20倍の配列を返します。 ただし、console.log(Check(users、0、20)); 'undefined'のみを返します。再帰関数の戻り値は「未定義」

私は間違っていますか?

var users = [23, 23, 23, 23, 23, 23, 23, 23, 23, 23]; 
console.log(Check(users, 0, 20)); 

function Check(ids, counter, limit){ 
    ids.push(23); 

    // Recursion 
    if (counter+1 < limit){ 
     Check(ids, counter+1, limit); 
    } 
    else { 
     console.log(ids); 
     return ids; 
    } 
} 
+2

'if'ブロックの' return'ステートメントは 'undefined'を意味しません。関数の最後に1つの 'return'ステートメントを入れ、' if'ステートメントに基づいて値を返すように設定すると、保守が簡単になるかもしれません – Ian

答えて

26

あなたはリクルートを入力した時点から結果を返すことを忘れました。

var users = [23, 23, 23, 23, 23, 23, 23, 23, 23, 23]; 
console.log(Check(users, 0, 20)); 

function Check(ids, counter, limit){ 
    ids.push(23); 

    // Recursion 
    if (counter+1 < limit){ 
     return Check(ids, counter+1, limit); // return here! 
    } 
    else { 
     console.log(ids); 
     return ids; 
    } 
} 

しかし、戻り値は、同様に、最初の配列を変え、あなたの関数「原因、役に立たないようです。

+0

実際のものから気を散らばさないようにできるだけ関数を単純化しました問題。どうもありがとう。 – Hedge