Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)

like image 496
Flion Avatar asked Aug 11 '14 12:08

Flion


People also ask

Can we use for in loop for array in JavaScript?

The for ... in syntax mentioned by others is for looping over an object's properties; since an Array in JavaScript is just an object with numeric property names (and an automatically-updated length property), you can theoretically loop over an Array with it.


1 Answers

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]);
}
like image 138
newfurniturey Avatar answered Oct 25 '22 21:10

newfurniturey