向 Javascript 数组添加箭头函数

Add an arrow function to a Javascript array

我有一个数组,其中包含箭头函数及其参数的列表。除一件事外,按预期工作。我在网页上有一个输入字段,我可以在其中输入新箭头函数的文本,然后单击一个按钮将其添加到数组中。挑战在于它作为字符串而不是函数添加,因此编译器在运行使用此函数数组的函数时会抛出错误。错误是 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) 中,我已经尝试了一些东西(等等)但还没有成功。任何想法都将不胜感激,并且也对能够实现相同目标的替代方法持开放态度,即使用参数存储函数,然后稍后调用它们。

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

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

const tempArr = [];

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

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

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