Javascript: add value to array on loop, which will also be included in the loop
Sorry if this is a duplicate, 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 loop type or data type) so that this will result in 1 2 3 4 5 during the loop (or in any order if all 5 numbers are there)
source to share
Usage Array.prototype.forEach()
will not apply callback to elements that are added or removed from the array at runtime. From the specification :
The range of items processed for each is set before the first call to callbackfn. The elements that are added to the array after the forEach call does not start with callbackfn.
However, you can use a canned loop for
conditionally 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]);
}
source to share
Better Alternative solution:
if (a.indexOf(1) >= 0) a.push(5);
a.forEach( ... );
OK, maybe not exactly better as it traverses the array twice. However, you have to consider why you are trying to modify the array by iterating over it in the first place. This is an unusual situation.
source to share