Foreach add to array javascript

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]

asked Aug 11, 2014 at 12:42

FlionFlion

9,85612 gold badges43 silver badges65 bronze badges

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]];
}

answered Aug 11, 2014 at 12:48

newfurnitureynewfurniturey

36.3k9 gold badges91 silver badges101 bronze badges

2

Obvious solution :

var a = [1,2,3,4];
for [var i=0; i= 0] a.push[5];
a.forEach[ ... ];

OK, maybe not strictly better, since it traverses the array twice. However you ought to consider why you're trying to modify the array whilst iterating over it in the first place. It's an unusual situation.

answered Aug 11, 2014 at 12:49

AlnitakAlnitak

329k70 gold badges402 silver badges485 bronze badges

3

SO this is a quick test that seems to work well :

var a = [1,2,3,4,5];
a.forEach [function [val,index,array] { 
 if [val == 5] {  
  array.push [6];
 };  
 console.log [val]; 
}];

answered Sep 7, 2017 at 0:00

1

a.forEach[function fn[item, index] {

if [item == 5] {  

  array.push [6];

 };

}]

Unheilig

16k193 gold badges67 silver badges96 bronze badges

answered Nov 2, 2018 at 7:21

GaneSHGaneSH

4872 gold badges5 silver badges16 bronze badges

var a = [1,2,3,4];
Object.keys[a].forEach[idx => {
    if[a[idx]==1] a.push[5];
    console.log[a[idx]];
}];

answered Oct 20, 2021 at 14:57

1

OP here. I've since learned that ES6 Sets do include items added during forEach.

So if you can use a set instead of an array, you can do:

var a = new Set[[1,2,3,4]];
a.forEach[function[value]{
  if[value == 1] a.add[5];
  console.log[value];
}];

which does indeed log 5 as well.

Just an alternative to the for loop. Of course Sets are different than arrays in several ways, so you'd need to understand the differences and how it effects your other code.

answered Sep 19 at 16:43

FlionFlion

9,85612 gold badges43 silver badges65 bronze badges

Chủ Đề