RanchiRhino RanchiRhino - 2 months ago 8
Javascript Question

Why this for loop is infinite loop despite a condition?

This function below is to create array slice and push is giving infinite loop. Can anybody try to justify that.

function MyFunction(arr, size) {
var newArr = [];

for(var i=0; i<arr.length; i+size)
{
newArr.push(arr.slice(i,i+size));

}
return newArr;
}


I am able to achieve my requirement with below while loop, although it seems almost similar.

function MyFunction(arr, size) {
var newArr = [];
var i = 0;
while(i < arr.length)
{
newArr.push(arr.slice(i,i+size));
i = i + size;
}
return newArr;

}



Sample Input:- myFunction(["a", "b", "c", "d"], 2);

Sample Output:- [["a", "b"], ["c", "d"]]

Answer

In your for loop you are never incrementing your variable i. That is it. i++ auto increments i but i+size doesn't.

it should be i=i+size or i+=size;

Hope this helps.

Edit

Your for loop should be:-

function MyFunction(arr, size) {
  var  newArr = [];

  for(var i=0; i<arr.length; i = i+size)    
   {  
    newArr.push(arr.slice(0,size));

   }  
  return newArr;
}
Comments