在函数中使用字符串作为参数名称?

时间:2018-06-15 13:54:57

标签: javascript

我遇到了一些独特的用例。给定像这样的数组["option", "option2", "option3"]我需要导出看起来像

的函数
function myFunc(option, option2, option3) {  }

这些函数的参数是动态的,我需要根据给定的字符串数组填充它们,我很好地通过它进行映射,但是在我将字符串"option"转换为参数名称的步骤中卡住了比如option

1 个答案:

答案 0 :(得分:4)

虽然您可以这样做,但我强烈建议您不要。它需要使用new Functioneval,这通常是值得避免的,因为它会启动JavaScript解析器(并且在错误的手中,通过提供任意代码执行来暴露漏洞)。我只是导出一个接受单个数组参数而不是离散参数的版本。人们可以使用离散参数轻松调用它:myFunc([firstValue, secondValue, thirdValue])

如果 数组中的文字来自安全来源,则可以使用new Function进行。

在ES2015 +中:

function realMyFunc(options) {
    // ...`options` is an array of the parameters
};
export const myFunc = new Function(...theArray, "return realMyFunc([" + theArray.join(", ") + "]);");

示例:

const theArray = ["option1", "option2", "option3"];

function realMyFunc(options) {
    console.log(options);
};
const myFunc = new Function(...theArray, "return realMyFunc([" + theArray.join(", ") + "]);");
console.log("myFunc:", myFunc);

myFunc("a", "b", "c");
.as-console-wrapper {
  max-height: 100% !important;
}

或者在ES5中:

var theArray = ["option1", "option2", "option3"];

function realMyFunc(options) {
    console.log(options);
};
var myFunc = new Function("return function(" + theArray.join(", ") + ") { return realMyFunc([" + theArray.join(", ") + "]); }")(); // Note the added () at the end
console.log("myFunc:", myFunc);

myFunc("a", "b", "c");
.as-console-wrapper {
  max-height: 100% !important;
}

但是,我只是导出一个接受单个数组参数的版本,而不是动态生成一个接受离散参数的版本。