【问题标题】:Add an arrow function to a Javascript array向 Javascript 数组添加箭头函数
【发布时间】:2021-11-13 21:39:31
【问题描述】:

我有一个数组,其中包含箭头函数及其参数的列表。除一件事外,按预期工作。我在网页上有一个输入字段,我可以在其中输入新箭头函数的文本,然后单击按钮将其添加到数组中。挑战在于它被添加为字符串而不是函数,因此编译器在运行使用此函数数组的函数时会引发错误。错误是TypeError: this.functionlist[i] is not a function

//I have a list of functions that I've pre-defined
functionlist = [
  () => functionA(parameterA, parameterB),
  () => functionB(parameterC, parameterD)
]

//I 'unpack' these functions and run them in another function
runAllFunctions() {
  for (let i = 0; i < functionlist.length; i++) {
    functionlist[i]()
  }
}

// I have some HTML code that uses a simple input field to capture the value of another arrow function and add it to the functionlist
//The input would be something like () => functionC(parameterE, parameterF)
//Have logic on the page to capture the input value and 'push' it to functionlist
//Value capture and push is working fine with the exception that I can clearly see that it's being added as a string whereas the other values in the array are of type function

我认为问题的根源在于输入是从 HTMLInputElement 捕获的,我需要在将其推送到我的数组之前以某种方式将其转换为类型函数。它在 TypeScript (Angular) 中,我已经尝试了一些东西(等等),但还没有运气。任何想法都将不胜感激,并且还可以采用其他方法来实现相同的目标,即存储带参数的函数,然后再调用它们。

【问题讨论】:

  • 你可以eval它。 (通常这是一个坏主意,但从输入字段添加箭头函数的整个想法听起来像是一些实验,所以......)
  • 我完全愿意接受其他更有价值的方法。用例是存储带有参数的函数列表,以便我以后可以运行它们。 'with their parameters' 似乎有点棘手,但如果您对一个好的方法有任何建议,我很想听听他们的意见!
  • functionC 或其他输入是否始终是现有/预定义函数?你能做一个下拉菜单让用户选择可以使用的功能吗?

标签: javascript arrays angular typescript arrow-functions


【解决方案1】:

如果可行,您可以这样做:

const creatFunc = (param1, param2) => {
   return function () {
     // do things here
     return `${param1}, ${param2}`;
   };    
};

const tempArr = [];

tempArr.push(creatFunc(1, 2));

console.log(tempArr[0]());

您可以利用闭包来保存参数并在将来执行。

【讨论】:

  • 感谢您抽出宝贵时间提供回复。我会试一试并报告
  • 这有帮助吗??
猜你喜欢
  • 1970-01-01
  • 2019-06-16
  • 2019-01-06
  • 2020-11-30
  • 2017-04-18
  • 2019-10-21
  • 2022-01-21
  • 1970-01-01
相关资源
最近更新 更多