增加一个数字并将其附加到函数

increment a number and attaching it to function

本文关键字:函数 数字 一个 增加      更新时间:2023-09-26

我有一个数字,它作为计数器存储在某个数据库中。每次页面运行时,计数器都会递增1。我检索这个数字没有问题,但我想要的是将这个数字附加到某个名称上,并强制执行一个新函数。

例如,

newGame0();newGame1();newGame2();

我该怎么做?

您可以将函数newGame0newGame1newGame2定义为对象的属性,使用括号表示法引用属性串联counter "newGame" + counter,调用函数

var counter = 0;
var obj = {
  newGame0: function() {
    console.log(counter)
  },
  newGame1: function() {
    console.log(counter)
  },
  newGame2: function() {
    console.log(counter)
  }
}
var interval = setInterval(function() {
  if (counter < 3) {
    // call `newGame0`, `newGame1`, `newGame2`
    obj["newGame" + counter](); 
    ++counter;
  } else {
    clearInterval(interval)
  }
}, 1500)

self['newGame' + counter] = function()
{
};

self['newGame' + counter] = existingFunctionName;

考虑在原型中编写一个带有方法的游戏对象,并在数组中保存一组游戏,而不是扰乱全局命名空间。