简体   繁体   English

根据给定变量的长度动态创建函数

[英]dynamically create the functions based on the length of the given variable

I have a function call “getDocID” which has been defined in some other JS library, for which we can pass a callback function myCallback. 我有一个在其他JS库中定义的函数调用“ getDocID”,我们可以为其传递回调函数myCallback。

To get the ID's for more than one we have to chain it, we need to call the function like following, which works fine. 要获得一个以上的ID,我们必须将其链接起来,我们需要像下面这样调用函数,该函数可以正常工作。

function setDocIds(){
    const testValues = ["2980", "2981","2982"];
    const optID = "someValue";
    var myCallback_2 = function (result2){
        var appID = result2.ID;
        document.getElementById("div_2").innerHTML = appID; 
    } 
    var myCallback_1 = function (result1){
        var appID = result1.ID;
        document.getElementById("div_1").innerHTML = appID; 
        getDocID(optID, testValues[2], myCallback_2);
    }
    var myCallback = function (result){
        var appID = result.ID;
        document.getElementById("emailtemplate").innerHTML = appID;
        getDocID(optID, testValues[1], myCallback_1);
    }
    getDocID(optID, testValues[0], myCallback);
}

Can anyone guide me to optimize the above code and to create the functions dynamically based on the length of the testValues. 谁能指导我优化上述代码并根据testValues的长度动态创建函数。

Using Array#forEach and scoping. 使用Array#forEach和作用域。

 function getDocID(id, num, callback){ callback({ID:`optId: ${id} and testVal: ${num}`}); } function setDocIds() { const testValues = ["2980", "2981", '2982']; const optID = "someValue"; testValues.forEach((n, i) => { getDocID(optID, n, function(result) { const appID = result.ID; const id = i === 0 ? "emailtemplate" : `div_${i}`; document.getElementById(id).innerHTML = appID; }); }); } setDocIds(); 
 <div id="emailtemplate"></div> <div id="div_1"></div> <div id="div_2"></div> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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