编写一个带n和函数f的函数,并返回一个函数g。
当你调用g()时,它最多调用f()n次。
离。
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
我的代码如下:
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次应调用f()3次。
提前感谢任何帮助。
答案 0 :(得分: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