[英]How to store same JS function with different parameters in array and call them?
I need to use a function like this for multiple times with different ids based on different conditions (eg select values). 我需要根据不同的条件(例如选择值)使用类似的函数多次使用具有不同id的函数。 I don't want to write a different function for every id because there will be lots of them in the future.
我不想为每个id编写不同的函数,因为将来会有很多。
var getValue = function(id){
var Element = document.getElementById(id);
if(Element){
if(Element.value){
return " " + Element.value;
}
return "";
}
return "";
}
I have an array including some other functions: 我有一个包含其他功能的数组:
FunctionList = [ SomeFunction, SomeFunction2 ];
Based on some conditions, I add getValue
function with different parameters to this array. 根据某些条件,我向此数组添加具有不同参数的
getValue
函数。
FunctionList.push(getValue(SomeId1));
FunctionList.push(getValue(SomeId2));
FunctionList.push(getValue(SomeOtherId));
In the end, I need to add outputs of my functions (which are strings) to another string. 最后,我需要将函数的输出(字符串)添加到另一个字符串。
var updateCode = function(){
var code = CodeHeader;
for (var i=0; i<FunctionList.length; i++){
code += FunctionList[i]();
}
return code;
}
But I am unable to use it like this since some items of array are not function names now. 但是我不能像这样使用它,因为数组的某些项现在不是函数名。 I like pure js solutions, but if it's not possible I can go for jQuery or so.
我喜欢纯js解决方案,但是如果不可能的话,我可以选择jQuery左右。
You can use bind
to create such a tailored function on the fly: 您可以使用
bind
即时创建这样的定制功能:
FunctionList.push(getValue.bind(null, SomeId1));
The first argument ( null
here) will act as this
during function execution. 第一个参数(此处为
null
)将在函数执行期间充当this
参数。
This differs from what you had: 这与您所拥有的不同:
FunctionList.push(getValue(SomeId1));
...as here you don't push a function, but the result of a function execution . ...如此处所示,您不是按功能,而是按功能执行的结果 。
bind
however, will not execute the function, but create a new one from the given function. 但是
bind
不会执行该功能,而是根据给定的功能创建一个新的功能。
In your example you call the same function with different arguments. 在您的示例中,您使用不同的参数调用相同的函数。 If that is always the case, you could also go for an array of only arguments:
如果总是这样,则还可以使用仅包含参数的数组:
argumentList.push(SomeId1); // Not the function, just the argument
// ...etc
And then updateCode
would become: 然后
updateCode
将变为:
var updateCode = function(){
var code = CodeHeader;
for (var i=0; i<argumentList.length; i++){
code += getValue(argumentList[i]);
}
return code;
}
... or shorter by using map
: ...或更短的
map
:
var updateCode = () => CodeHeader + argumentList.map(getValue).join("");
As in your getValue
function, you prefix the returned value with a space, you could omit that prefix, and just use .join(" ")
in the above one-liner. 就像在
getValue
函数中一样,您为返回的值添加一个空格前缀,可以省略该前缀,而只需在上述单行代码中使用.join(" ")
。 The downside is that it would not deal the same way with empty return values. 缺点是,对于空的返回值,它不会以相同的方式处理。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.