Home > Software engineering >  How to clear a variable after one run in a for loop
How to clear a variable after one run in a for loop

Time:09-19

with my code I fetch a json from my server and display the data on the frontend. That is the json https://pastebin.com/56YEnY4Z

The code is generating a html list.

for (var i = 0; i < data.array.length; i  ) {
                if(data.array[i].orderStatus == 0)
                {
                    statusName = 'Neu erstellt';
                     statusColor = 'text-sky-500';
                } else if(data.array[i].orderStatus == 1) {
                    statusName = 'In bearbeitung';
                    statusColor = 'text-orange-500';
                }
                for(var k = 0; k < data.array[i].foodArray.length; k  ) {
                    li  = `<li ><span>`  data.array[i].foodArray[k].name  `</span><span>`  data.array[i].foodArray[k].price  ` EUR</span></li>`;
                }

                list = `<ul >`  li  `</ul>`;

The problem I got is that the first run is smooth, after that old data is getting in the second generated list. Is there a function I can use to empty the var li after one for loop run?

** I declared the variables, that code is just a snippet from the original **

CodePudding user response:

You can clear your li inside the second loop if k==0, meaning every time you finish the outer loop you reset the li as k will be equal to 0 after each iteration of the outer loop

for(var k = 0; k < data.array[i].foodArray.length; k  ) {
   if(k == 0)
      li = '';
   
   li  = `<li ><span>`  data.array[i].foodArray[k].name  `</span><span>`  data.array[i].foodArray[k].price  ` EUR</span></li>`;
}

Or simply add at the start of your outer loop

li = '';
  • Related