执行前回调需要调用的次数

Number of times the callback needs to be called before executed

我收到了 4 个面试问题,其中之一是:

Write a function after that takes the number of times the callback needs to be called before being executed as the first parameter and the callback as the second parameter.

function after(count, func) {
  // Implement the 'after' function
}

var called = function() { console.log("hello") };
var afterCalled = after(3, called);

afterCalled(); // -> nothing is printed
afterCalled(); // -> nothing is printed
afterCalled(); // -> 'hello' is printed

我解决问题的方法是这样的:

function after(count, cBack) {
  localStorage.setItem("aCount", count);
  return function () {
    let currCount = localStorage.getItem("aCount");

    if (currCount == 1) {
      cBack();
    } else {
      localStorage.setItem("aCount", --currCount);
    }
  };
}

let called = function () {
  console.log("hello");
};

let afterCalled = after(5, called);

afterCalled();
afterCalled();
afterCalled();
afterCalled();
afterCalled();

我的意思是,代码按预期工作,但我感觉 localStorage 不是这样。我错过了什么吗?我可以使用或 'should' 用来解决这个问题的回调函数中有什么东西吗?如果是这样,我应该看什么?

他们可能希望您使用通过调用 after 形成的闭包(见评论):

let after = (count, callback) => {
    return () => {
        // Has our count reached one?
        if (count <= 1) {
            // Yes, call the callback
            callback();
        } else {
            // No, decrement the count
            --count;
        }
    };
};

let called = function () {
  console.log('hello')
};

let afterCalled = after(5, called);

afterCalled();
afterCalled();
afterCalled();
afterCalled();
afterCalled();

只要afterreturns的函数存在,count参数就一直存在,因为函数afterreturns是一个closure 在创建它的上下文中。所以你可以用它来记住调用的次数。