I have a JavaScript array of length 3
arr = [1, 3, 8];
Is there a way to add elements to arr
while I am iterating over it? I want to insert two values 10 and 20 into the existing arr
. Can I do it like this? The newly added elements, 10 and 20, must also be looped over in the same for in loop.
for(var i in arr) {
if( i == 0 ) {
arr[length + 0] = 10;
arr[length + 1] = 20;
}
}
Or, what is the correct way to add elements to an array while iterating and making sure that the newly added elements will also be looped over?
You could use a for
statement and check the length
while iterating the array.
With for ... in
statement, iteration of new elements is not granted.
Properties added to the object over which iteration is occurring may either be visited or omitted from iteration. In general it is best not to add, modify or remove properties from the object during iteration, other than the property currently being visited.
var array = [1, 3, 8],
i;
for (i = 0; i < array.length; i++) {
console.log(array[i]);
if (i === 0) {
array.push(10, 20);
}
}