简体   繁体   中英

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). I don't want to write a different function for every id because there will be lots of them in the future.

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.

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.

You can use bind to create such a tailored function on the fly:

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

The first argument ( null here) will act as this during function execution.

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.

Alternative

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:

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 :

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. The downside is that it would not deal the same way with empty return values.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM