【问题标题】:Javascript Function that Counts How Many Times the Function was Called [duplicate]计算函数被调用次数的Javascript函数[重复]
【发布时间】:2021-06-10 21:52:44
【问题描述】:

我的任务是创建一个不带参数的名为 countTimesCalled 的箭头函数。它必须返回每次调用它的次数。该函数应该是完全独立的。

这是我目前所拥有的,我希望它是这样的,但我不知道如何初始化计数器。任何帮助将不胜感激!

countTimesCalled = () => {
counter = 0;
if (counter == undefined){
    counter = 1;
    return(this.counter)
} else {
    return(this.counter++)
}

【问题讨论】:

  • 闭包是你的朋友,想想一个 iife 返回你的函数。另一种方法是将计数器存储在函数本身上。

标签: javascript function counter


【解决方案1】:

您可以将一个属性附加到函数本身以跟踪计数:

const countTimesCalled = () => {
  if (!countTimesCalled.count) {
    countTimesCalled.count = 0;
  }

  return ++countTimesCalled.count;
};

console.log(countTimesCalled());
console.log(countTimesCalled());
console.log(countTimesCalled());

【讨论】:

  • 没有箭头函数,您可以创建一个不依赖于外部闭包的自引用:let f = function g() { g.counter = (g.counter ?? 0) + 1; return g.counter; }; f(); let h = f; f = void 0; h(); - 可以更改包含该函数的变量,而不会破坏代码。或者,当然可以始终使用 iife 和闭包 ;)
  • @ASDFGerte 答案中没有任何内容取决于它是箭头函数。你可以用function countTimesCalled() { ... }做同样的事情
  • 我的意思不是“答案有问题”,只是作为旁注。不同之处在于,您将得到一个表达式,它不使用闭包中的外部变量。即使使用function c() { if (!c.c) c.c = 0; return ++c.c; }(作为函数声明语句),也有人可以分配c = void 0;,调用该函数会抛出异常。
  • OP 无论如何都明确要求提供箭头功能,所以它只是一个注释。
【解决方案2】:

你可以给函数本身添加一个属性来保存它的使用次数

const countTimesCalled = () => {
  countTimesCalled.counter=!countTimesCalled.counter?0:countTimesCalled.counter;
  return ++countTimesCalled.counter ;
}; 

OR 没有箭头函数。

function countTimesCalled () {
  if (!this.counter) {
    this.counter = 0;
  }

  return ++this.counter;
};   

注意:但第一个代码是最好的。

【讨论】:

  • 这非常有帮助,非常感谢
  • @AnnaBotts ... abdo afage's 当然不应该使用第二个版本,因为通过this.counter 它会在全局范围内创建一个counter 变量,这被认为不是最简洁的编码风格。
  • 感谢您的留言 :)
  • @abdoafage ... 实际上,该注释可以被视为从您的答案中删除第二个示例的提示。基于 this 的方法在环境箭头函数或函数声明/语句/表达式中都没有帮助。
【解决方案3】:

创建一个immediately invoked function expressionuses arrow functions 并返回您的计数箭头函数。这样您就不需要函数来引用自身,并且计数与外部完全隔离:

const countTimesCalled = (count => () => ++count)(0);
  
  
console.log(countTimesCalled());
console.log(countTimesCalled());
console.log(countTimesCalled());
console.log(countTimesCalled());
console.log(countTimesCalled());
const countTimesCalled = (
  count => // <-------------<-------------<-------------+
    () => ++count //                                    |
//  ^^^^^^^^^^^^^ gets assigned to `countTimesCalled`   |
)(0); // -->- passed as argument ->---------->----------+

它的扩展版本如下:

const countTimesCalled = (
  () => {
    let count = 0;

    return () => {
      count += 1;

      return count;
    };
  }
)();
  
  
console.log(countTimesCalled());
console.log(countTimesCalled());
console.log(countTimesCalled());
console.log(countTimesCalled());
console.log(countTimesCalled());

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-11-19
    • 2018-12-29
    • 1970-01-01
    • 2021-01-09
    • 2013-07-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多