Skip to content
Advertisement

Javascript: add value to array while looping that will then also be included in the loop

Sorry if this is a dupplicate, can’t seem to find it.

var a = [1,2,3,4];
a.forEach(function(value){
  if(value == 1) a.push(5);
  console.log(value);
});

I wonder if there is a way (any sort of loop or datatype) so that this will ouput 1 2 3 4 5 during the loop (or in any order, as long as all the 5 numbers are in there)

Advertisement

Answer

Using Array.prototype.forEach() will not apply the callback to elements that are appended to, or removed from, the array during execution. From the specification:

The range of elements processed by forEach is set before the first call to callbackfn. Elements which are appended to the array after the call to forEach begins will not be visited by callbackfn.

You can, however, use a standard for loop with the conditional checking the current length of the array during each iteration:

for (var i = 0; i < a.length; i++) {
    if (a[i] == 1) a.push(5);
    console.log(a[i]);
}
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement