2016-10-18 27 views
-3

番号nと関数fをとり、関数gを返す関数を記述します。JSコードで解決できない

g()を呼び出すと、最大でn回f()が呼び出されます。

ex。 BELOW

function log() { 
    console.log('called log'); 
} 
var onlyLog = only(3, log); 
onlyLog(); -> outputs 'called log' to console 
onlyLog(); -> outputs 'called log' to console 
onlyLog(); -> outputs 'called log' to console 
onlyLog(); -> does nothing 
onlyLog(); -> does nothing 

MY CODE:

toolbox.only = function(n, f) { 
    for (var i = 0; i <= n; i++) { 
    var called = false; 
    return function() { 
     if (!called) { 
     f(); 
     called = true; 
     } 
    } 
    } 
} 

私のコードは次の試験に合格されていません:だけを呼び出す(3、f)は3回以上は()3回のFを呼び出す必要があります。

ご協力いただきありがとうございます。

以下、これを試してみてください、私はあなたがオーバー問題を考えていたと思います

+2

まあ、まず第、 'ループ内return'ingすると、その終了させます即座にループします。つまり、ループは本質的に1回の反復しか実行しません。 –

+0

まず基礎から始めましょう。本当に 'for'ループが必要だと思いますか?あなたは何度も何度も何度も繰り返していますか?なぜあなたのコードは1回の呼び出しでしか機能しないと思いますか? –

+0

Oo、私はfunctionfをn回呼びたいと思っていましたが、私はそれを誤解しています。なぜ私のループもループしないだろうと思う。私は前に、それを指摘してくれたことに感謝しなかった。なぜなら、それは私が解決しようとしていたものだったからです(なぜなら、私は質問を誤読していたからです) – Alex

答えて

1

..

// Write a function that takes a number n and a function f, and returns a function g. 
 
// When you call g() it calls f() at most n times. 
 

 
// ex. 
 
// function log() { 
 
// console.log('called log'); 
 
// } 
 
// var onlyLog = only(3, log); 
 
// onlyLog(); -> outputs 'called log' to console 
 
// onlyLog(); -> outputs 'called log' to console 
 
// onlyLog(); -> outputs 'called log' to console 
 
// onlyLog(); -> does nothing 
 
// onlyLog(); -> does nothing 
 

 
var only = function(n, f) { 
 
    return function() { 
 
    if (n) { 
 
     n --; 
 
     f(); 
 
    } 
 
    } 
 
} 
 

 
function log() { 
 
    console.log('called log'); 
 
} 
 
var onlyLog = only(3, log); 
 
onlyLog();// -> outputs 'called log' to console 
 
onlyLog();// -> outputs 'called log' to console 
 
onlyLog();// -> outputs 'called log' to console 
 
onlyLog();// -> does nothing 
 
onlyLog();// -> does nothing

関連する問題