Tengo un conjunto de dos para bucles. Los elementos se compensan con un conjunto inicial de elementos numberOfInputs . Me gustaría refactorizarlos en un solo ciclo. cada matriz tiene el mismo número de elementos. Ambos están establecidos por el mismo número de numberOfInputs .
Descubrí cómo hacer esto manualmente restando el desplazamiento cuando sea necesario e incrementando en 1 cuando sea necesario.
// number of inputs start out as 2. var numberOfInputs = 2; // initialize blank html html = ''; //create key inputs for (let i = numberOfInputs; i < elArray.length+numberOfInputs; i++){ html += '<div id="s'; id = (1+i-numberOfInputs); html += id; html +='\" class=\"draggyBox-small\">'; html += elArray[i-numberOfInputs]; html +='</div>\n'; } //create description inputs html += '<table id=\"tablestyle\">' for (let i = numberOfInputs; i < dlArray.length+numberOfInputs; i++){ html += '<td id="row'; id = (1+i-numberOfInputs); html += id; html +='">\n'; html += '\t\t<div id=\"t'; html += id; html +='" class=\"ltarget\"></div>\n \t</td >\n \t<td id=\"d2\">' html +=dlArray[i-numberOfInputs]; html +='</td >\n </tr>\n'; } html += '</table>';Tenga un ciclo que cree dos fragmentos de HTML ( html_1 y html_2 ) y agréguelos después de que finalice el ciclo:
// initialize blank html html = ''; //create key inputs var html_1 = '' var html_2 = '<table id=\"tablestyle\">' for (let i = numberOfInputs; i < elArray.length+numberOfInputs; i++){ html_1 += '<div id="s'; var id = (1+i-numberOfInputs); html_1 += id; html_1 +='\" class=\"draggyBox-small\">'; html_1 += elArray[i-numberOfInputs]; html_1 +='</div>\n'; html_2 += '<td id="row'; html_2 += id; html_2 +='">\n'; html_2 += '\t\t<div id=\"t'; html_2 +=i-numberOfInputs; html_2 +='" class=\"ltarget\"></div>\n \t</td >\n \t<td id=\"d2\">' html_2 +=dlArray[i-numberOfInputs]; html_2 +='</td >\n </tr>\n'; } html = html_1 + html_2 + '</table>'También puede simplificar esto con literales de plantilla .
Tener dos bucles for que se ejecutan en el mismo índice está bien. No cambia significativamente el rendimiento y es más fácil de entender. Sin embargo, hay otras refactorizaciones que podrían realizarse para mejorar tanto el rendimiento como la legibilidad.
Nota: siempre estás restando numberOfInputs , por lo que no hay razón para agregarlo para empezar.
// assuming `html` and `elArray` had been set earlier // and that `elArray` is an array of strings let top = elArray.map((v,i) => `<div id="s${i+1}" class="draggyBox-small">${v}</div>` ).join('\n'); let bottom = elArray.map((v,i) => `<tr> <td id="row${i+1}"> <div id="t${i}" class="ltarget"></div> </td > <td id="d2">${v}</td > </tr>` ).join('\n'); html = `${top} <table id="tablestyle"> ${bottom} </table> `;Referencias: