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)
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]);
}
Obvious solution:
var a = [1,2,3,4];
for (var i=0; i<a.length; i++){
var value = a[i];
if(value == 1) a.push(5);
console.log(value);
}
Since you seem to be using Harmony, how about a generator like this:
function *iter(array) {
for (var n = 0; n < array.length; n++)
yield array[n];
}
and then
var a = [1,2,3,4];
for(var p of iter(a)) {
if(p == 1) a.push(5)
console.log(p)
}
prints 1 2 3 4 5
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.
SO 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);
});