skip to Main Content

I have a small problem that I haven’t been able to solve so far.
I wish I could shorten this piece of code, but I tried a for loop and failed.
Here is my code to shorten:

let Mrow = table.insertRow(12);
let Mcell0 = Mrow.insertCell(0);
let Mcell1 = Mrow.insertCell(1);
let Mcell2 = Mrow.insertCell(2);
let Mcell3 = Mrow.insertCell(3);
let Mcell4 = Mrow.insertCell(4);
Mcell0.innerHTML = "Totals";
Mcell1.innerHTML = Msum1; 
Mcell2.innerHTML = Msum2;
Mcell3.innerHTML = Msum3;
Mcell4.innerHTML = Msum4;type here

This is what i have tried:

for(let cell = 0; cell < 5; cell++){
    let Mrow = table.insertRow(12);
    let Mcell0 = Mrow.insertCell(cell);
    Mcell0.innerHTML = "Totals";
}

Unfortunately in this way I can’t figure out how to do it.
However, by proceeding in this way, the code lengthens unnecessarily.
I know it might sound trivial, but I can’t figure out how to do it and I’m wasting a lot of time.
Thank you all.
Sorry for the bad English.

2

Answers


  1. You can safely omit the indexes and eliminate temp variables:

    let Mrow = table.insertRow(12);
    Mrow.insertCell().innerHTML = "Totals"
    Mrow.insertCell().innerHTML = Msum1
    Mrow.insertCell().innerHTML = Msum2
    Mrow.insertCell().innerHTML = Msum3
    Mrow.insertCell().innerHTML = Msum4
    

    Also, your serially number variables MsumXXX should probably be an array. If you can do that, you can reduce the last part to something like

    for (let sum of MsumArray)
        Mrow.insertCell().innerHTML = sum
    
    Login or Signup to reply.
  2. one way of defining constant and extract it, it looks neater and code maintainability.
    const createCells= {0:'Totals',1:'Msum1',2:'Msum2'}; for(let [keys,values] of Object.entries(createCells)) {dsdsd console.log(keys,values) }

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search