[英]How do I store functions with their parameters in an array and execute them sequentially?
[英]How to store same JS function with different parameters in array and call them?
我需要根据不同的条件(例如选择值)使用类似的函数多次使用具有不同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(" ")
。 缺点是,对于空的返回值,它不会以相同的方式处理。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.