Anu Anu - 7 months ago 6
Javascript Question

How to make a for loop dynamic?

I am have 2 arrays like

[2,3]
and
[1000,1200,500,600,1600]
.
I need to write a
for loop
for this like.

1.start index from 0 and end index at 2.

2.start time from 2 and end index with sum of first 2 element (2+3)= 5.

var arr = [2,3];
for(var i = 0; i<arr.length;i++)
{
//this loop runs 2 time
for(var j = 0 ; j < 2 ; j++)//for the first time
for(var j = 2 ; j < 5 ; j++)//for the second time

}


How to make this dynamic for loop? Can someone please help me code?

Answer

This would do what you want and would be extendible.

var arr = [2,3];
var sum = 0;
for(var i = 0; i<arr.length;i++)
{
   sum += arr[i]
   if (i === 0) {
      for(var j = 0 ; j < arr[0] ; j++) 
         // Do first thing
   }
   if (i > 0) {
      for(var j = arr[0] ; j < sum ; j++)
         // Do second thing
   }
}
Comments