gpt4 book ai didi

javascript - 如何在数组中存储具有不同参数的相同JS函数并调用它们?

转载 作者:行者123 更新时间:2023-12-02 23:03:31 25 4
gpt4 key购买 nike

我需要根据不同的条件(例如选择值)使用不同的 id 多次使用这样的函数。我不想为每个 id 编写不同的函数,因为将来会有很多这样的函数。

var getValue = function(id){

var Element = document.getElementById(id);

if(Element){
if(Element.value){
return " " + Element.value;
}
return "";
}
return "";
}

我有一个包含一些其他函数的数组:

FunctionList = [ SomeFunction, SomeFunction2 ];

根据一些条件,我向该数组添加了具有不同参数的 getValue 函数。

FunctionList.push(getValue(SomeId1));
FunctionList.push(getValue(SomeId2));
FunctionList.push(getValue(SomeOtherId));

最后,我需要将函数的输出(字符串)添加到另一个字符串。

var updateCode = function(){
var code = CodeHeader;
for (var i=0; i<FunctionList.length; i++){
code += FunctionList[i]();
}
return code;
}

但是我无法像这样使用它,因为数组的某些项现在不是函数名称。我喜欢纯 js 解决方案,但如果不可能,我可以选择 jQuery 等。

最佳答案

您可以使用bind动态创建这样的定制函数:

FunctionList.push(getValue.bind(null, SomeId1));

第一个参数(此处为null)将在函数执行期间充当this

这与您所拥有的不同:

FunctionList.push(getValue(SomeId1));

...在这里,您推送的不是函数,而是函数执行的结果bind 但是,不会执行该函数,而是根据给定函数创建一个新函数。

替代方案

在您的示例中,您使用不同参数调用相同函数。如果情况总是如此,您也可以选择仅包含参数的数组:

argumentList.push(SomeId1); // Not the function, just the argument
// ...etc

然后 updateCode 将变为:

var updateCode = function(){
var code = CodeHeader;
for (var i=0; i<argumentList.length; i++){
code += getValue(argumentList[i]);
}
return code;
}

...或更短的使用map:

var updateCode = () => CodeHeader + argumentList.map(getValue).join("");

就像在 getValue 函数中一样,您在返回值前添加一个空格作为前缀,您可以省略该前缀,只需在上面使用 .join("")单行。缺点是它不会以相同的方式处理空返回值。

关于javascript - 如何在数组中存储具有不同参数的相同JS函数并调用它们?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57698201/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com