JS代码无法解决

JS code cannot solve

本文关键字:解决 代码 JS      更新时间:2023-09-26

写一个函数,取一个数字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次。

如有任何帮助,我们将不胜感激,并提前表示感谢。

我觉得你想得太多了。。

请尝试下面的操作。。

// 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